【发布时间】:2017-10-25 19:00:01
【问题描述】:
从java 中的服务器程序读取时,我得到了模棱两可的输出:
byte [] mybytearray = new byte [content_length];
InputStream inputStream = clientSocket0.getInputStream(); //Getting input
from peer0
FileOutputStream fileOutputStream = new FileOutputStream(fileDownloaded);
//Sending the output to local directory
BufferedOutputStream bufferedOutputStream = new
BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(mybytearray,0,content_length);
System.out.println("First read : " +bytesRead);
current = bytesRead;
if(bytesRead!=content_length) {
current = bytesRead;
do {
System.out.println(current +"-Current");
System.out.println("Read it : "+(mybytearray.length-current));
bytesRead =
inputStream.read(mybytearray, current, (mybytearray.length-current));
System.out.println("***"+bytesRead);
if(bytesRead == -1) {
//current = content_length;
break;
}
else
current += bytesRead;
} while(current < content_length );
}
bufferedOutputStream.write(mybytearray, 0 , current);
bufferedOutputStream.flush();
bufferedOutputStream.close();
inputStream.close();
inFromServer0.close();
它为某些文件提供以下输出:
内容长度 33996
C:\Users\Sumit\git\IP_Task2\Task1\Peer1/rfc8183.txt.pdf
初读:24356
24356-电流
阅读:9640
***-1
循环中的 bytesRead 为 -1,因此无法创建正确的文件。
【问题讨论】:
-
请正确格式化您的代码!如果您使用的是最新版本的 Java,请考虑使用 try-with-resources 而不是手动调用
InputStream.close()。