我正在通过套接字发送文件并尝试将其写入接收方的文件中。
我见过这样的例子:
int bytesRead = 0;
while (bytesRead != -1)
{
bytesRead = networkInputStream.read(buffer, 0, diskBlockSizeEstimate);
bufferedOutputStream.write(buffer, 0, bytesRead);
}
但是,从 http://developer.android.com/reference/java/io/InputStream.html#read%28byte[]%29 听起来,当到达流的末尾时 .read 返回 -1 。然后当使用 -1 调用 .write 时,会引发异常。我是否必须实现“if(bytesRead==-1) set bytesToRead = fileSize - totalBytesRead”或类似这样的逻辑:
int fileSize = ... get filesize from sender ...;
int totalBytesRead = 0;
int bytesRead = 0;
while (bytesRead != -1)
{
bytesRead = networkInputStream.read(buffer, 0, diskBlockSizeEstimate);
if(bytesRead == -1)
{
bufferedOutputStream.write(buffer, 0, fileSize - totalBytesRead);
totalBytesRead += fileSize - totalBytesRead;
}
else
{
bufferedOutputStream.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
}
另外,使用 while(totalBytesRead != fileSize) 而不是 while(bytesRead != -1) 会更好吗?