好的,所以我正在制作一个具有服务器和客户端的 Java 程序,并且我正在从服务器向客户端发送一个 Zip 文件。我已经把文件发下来了,差不多了。但是收到后我发现了一些不一致之处。我的代码并不总是获得完整的存档。我猜它会在 BufferedReader 完成之前终止。这是客户端的代码:
public void run(String[] args) {
try {
clientSocket = new Socket("jacob-custom-pc", 4444);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedInputStream(clientSocket.getInputStream());
BufferedReader inRead = new BufferedReader(new InputStreamReader(in));
int size = 0;
while(true) {
if(in.available() > 0) {
byte[] array = new byte[in.available()];
in.read(array);
System.out.println(array.length);
System.out.println("recieved file!");
FileOutputStream fileOut = new FileOutputStream("out.zip");
fileOut.write(array);
fileOut.close();
break;
}
}
}
} catch(IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
那么在写入文件之前,我如何才能确定完整的归档文件就在那里?
最佳答案
在发送端写入文件大小,然后再开始写入文件。在阅读方面 阅读文件大小,以便了解预期的字节数。然后调用 read 直到你得到你期望的一切。使用网络套接字,可能需要多次调用才能读取发送的所有内容。当您的数据变大时尤其如此。
关于java - 如何确保通过套接字流接收到整个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767656/