//视屏中毕老师讲到的上传到服务器文件与上传文件名相同,写出来了,但有一点疑问,在下面。
import java.io.*;
import java.net.*;
class TcpCopyPicClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.0.125",10008);
File file = new File("D:\\tra\\Lamp.java");
String fileName = file.getName();//获取文件名
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);//这儿用BufferedWriter 该怎么写呢?
pw.println(fileName);//写入输出流
FileInputStream fis = new FileInputStream(file);
OutputStream fosOut = s.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf))!=-1)
{
fosOut.write(buf,0,len);
}
s.shutdownOutput();
BufferedReader frIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String end = frIn.readLine();
System.out.println(end);
fis.close();
s.close();
}
}
class TcpCopyPicServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10008);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"连接上了");
BufferedReader brIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String fileName = brIn.readLine();//获取文件名
File file = new File("E:\\java\\"+fileName);//封装到文件
InputStream fisIn = s.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
int len = 0;
byte[] buf = new byte[1024];
while((len=fisIn.read(buf))!=-1)
{
fos.write(buf,0,len);
}
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);//这儿也和上面类似 如果我要用BufferedWriter怎么实现呢,我弄得一直抛出异常。
pw.println("上传成功");
fos.close();
s.close();
ss.close();
}
}
|
|