0

我正在通过套接字发送文件并尝试将其写入接收方的文件中。

我见过这样的例子:

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) 会更好吗?

4

1 回答 1

3

我对这类事情的典型循环如下所示:

int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
    output.write(buffer, 0, bytesRead);
}

虽然我通常不喜欢在条件(循环或)中执行赋值,但if对于这个特定用例来说,这是一种足够常见的模式,您很快就会习惯它。

请注意,read此处仅适用于整个缓冲区-我不确定您为什么要将其限制为diskBlockSizeEstimate...或者如果您确实希望将其作为每次读取的最大数量,只需创建具有该大小的缓冲区开始。

于 2013-10-03T15:53:10.317 回答