【发布时间】:2015-10-26 00:40:57
【问题描述】:
我的文件从服务器传输到客户端时出现问题。问题是即使文件有多大,最后一个字节也不会被传输。假设我想下载一个 56kb 的文件,例如我只收到 35kb。
我会为你提供一些代码 sn-ps,也许有人会看到任何错误。
发件人:
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);
}
}
接收者:
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);
}
}
欢迎任何帮助,谢谢。
【问题讨论】:
-
查看这篇文章和该文章中的链接:stackoverflow.com/questions/32251895/… & coderanch.com/t/556838/java/java/…
-
在发送方使用固定长度的缓冲区。无需将其与文件长度相关联。接收代码中的 1025 就足够了,尽管更大也不会受到伤害。