文件上传案例
分析:
客户端读取本地文件,把文件上传到服务器
1.客户端使用本地的字节输入流,读取要上传的文件
2.客户端使用网络字节输出流,把读取到的文件上传到服务器
服务器把上传的文件保存到硬盘上
1.服务器使用网络字节输入流,读取客户端上传的文件
2.服务器使用本地字节输出流,把读取到的文件保存到硬盘上
3.服务器使用网络字节输出流,回写给客户端一个上传成功
4.客户端使用网络字节输入流读取服务器回写的数据
服务器端
public class Sever {
public static void main(String[] args) throws IOException {
ServerSocket SSo = new ServerSocket(8888);
Socket Soc = SSo.accept();
InputStream FIS = Soc.getInputStream(); //网络读取
FileOutputStream FOS = new FileOutputStream("D:\\Sever\\1.jpg"); //本地输出文件
int len = 0;
byte[] bytes = new byte[1024];
while ((len = FIS.read(bytes)) != -1){
FOS.write(bytes,0,len);
}
Soc.getOutputStream().write("上传成功".getBytes());
SSo.close();
FOS.close();
}
}
客户端
public class Client {
public static void main(String[] args) throws IOException {
FileInputStream InS = new FileInputStream("D:\\Client\\1.png");
Socket so = new Socket("127.0.0.1",8888);
OutputStream OpS = so.getOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = InS.read(bytes)) != -1){
OpS.write(bytes,0,len);
}
so.shutdownOutput();
InputStream ips = so.getInputStream(); //网络读取
int lens = 0;
while((lens = ips.read(bytes)) != -1){
System.out.println(new String(bytes,0,lens));
}
InS.close();
so.close();
}
}