续上次讲过UDP传输文件,这次简要讲下关于TCP文件传输的发送端与接收端.tcp传输主要关键地方就是文件末尾的处理
发送端代码:
private void sendFile(File f) throws Exception {
oos.writeUnshared(f);
oos.writeLong(f.length());
FileInputStream fins = new FileInputStream(f);
byte[] buf = new byte[8192];
int size = 0;
while ((size = fins.read(buf)) != -1) {
oos.write(buf, 0, size);
}
System.out.println("发送方发送文件:" + f + " 完毕");
oos.flush();
fins.close();
}
接收端代码:
/**
* 处理对方发过来的文件
*/
private void doReceiveFile(String savePath) throws Exception {
File f = (File) ois.readUnshared();//文件
long len = ois.readLong();
System.out.println("接收方 收到发送方的文件:" + f + " 文件大小:" + len);
File file = new File(savePath, f.getName());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
BufferedOutputStream fous = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[8192];
int lengths = -1;//实现每次接收到的数组长度
int accepts = 0;//当前已经传的文件长度
int canRead = (int) (len - accepts - 8192 < 0 ? len - accepts : 8192);//处理文件末尾
while ((lengths = ois.read(buffer, 0, canRead)) > 0) {
fous.write(buffer, 0, lengths);
accepts += lengths;
canRead = (int) (len - accepts - 8192 < 0 ? len - accepts : 8192);
}
fous.close();
System.out.println("接收方接收文件完毕");
}