[英]Java socket file transfer - not complete file
I have a problem with my file transfer from a server to client. 我从服务器到客户端的文件传输有问题。 The thing is that even how big the file is, the last bytes will not be transferred.
问题是,即使文件有多大,最后的字节也不会被传输。 Let say I want to download a file for 56kb, then I only receives 35kb for example.
假设我要下载一个56kb的文件,例如,我只收到35kb。
I will provide you with some code snippets and maybe someone could see anything that is wrong. 我将为您提供一些代码片段,也许有人可以看到任何错误的内容。
Sender: 发件人:
public void sendFile(String fileName, Socket socket) {
try {
try {
File transferFile = new File(fileName);
byte[] bytearray = new byte[(int) transferFile.length()];
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
OutputStream os = socket.getOutputStream();
int bytesRead = 0;
while (-1 != (bytesRead = bin.read(bytearray, 0, bytearray.length))) {
os.write(bytearray, 0, bytesRead);
}
bin.close();
os.flush();
socket.close();
} catch (IOException e) {
System.out.println("error " + e);
}
} catch (Exception ex) {
System.out.println("error " + ex);
}
}
Receiver: 接收器:
public void downloadFile(Socket socket, String fName) {
try {
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(fName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int count;
byte[] buffer = new byte[1024];
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
bos.close();
} catch (Exception e) {
System.out.println("Error " + e);
}
}
Any help is welcome, thank you. 欢迎任何帮助,谢谢。
while ((count = is.read(buffer)) > 0)
will break the loop if is.read()
returns zero. 如果
is.read()
返回零, while ((count = is.read(buffer)) > 0)
将中断循环。
However, you should not assume that the end of the file has been reached if zero is returned, because according to the documentation, zero is a perfectly valid value to return. 但是,如果返回零,则不应假定已到达文件末尾,因为根据文档,零是要返回的完全有效的值。
You should keep reading until -1
is returned. 您应该继续阅读直到返回
-1
。
Furthermore, after closing your BufferedOutputStream bos
you should also close your FileOutputStream fos
. 此外,在关闭
BufferedOutputStream bos
之后,您还应该关闭FileOutputStream fos
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.