
Java文件传输
对于文件传输主要就是:将文件以流的形式从客户端把文件提交到服务器端的过程。
主要分为以下两个步骤:客户端发送文件和服务端接收文件。
客户端发送文件
假设现在要把一张照片文件传输给另一方,首先是客服端找到文件地址,通过流形式传输出去。
如下所示:
FileInputStream fileStream = new FileInputStream("Local_File_Path/mikechen.png");
byte[] bytes = new byte[1024];
int i = 0;
while ((i = fileStream.read(bytes)) != -1) {
outStream.write(bytes);
}
// 写入结束标记,禁用此套接字的输出流,之后再使用输出流会抛异常
socket.shutdownOutput();
// 接收服务端响应结果
System.out.println("server-resp:"+new String(bytes,0,readLen));
服务端接收文件
客户端发送了文件后,然后就是服务端来接收这个文件,并处理。
如下所示:
// 接收客户端图片
FileOutputStream fileOutputStream = new FileOutputStream("Local_File_Path/mikechen.png");
byte[] bytes = new byte[1024];
int i = 0;
while ((i = inStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, i);
}
// 响应客户端文件处理结果
outStream.write("file-save-success".getBytes());
mikechen睿哥
10年+一线大厂架构实战经验,就职于阿里、淘宝等一线大厂,操盘多个亿级大厂核心项目。