从InputStream复制到BufferedOutputStream

时间:2013-10-03 15:50:15

标签: java android inputstream

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

我见过这样的例子:

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

1 个答案:

答案 0 :(得分:3)

我这种事情的典型循环如下:

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

虽然我不通常喜欢在条件(循环或if)内执行赋值,但对于这个特定用例来说,这是一个非常常见的模式,你已经习惯了快。

请注意,这里的read仅用于整个缓冲区 - 我不确定您为什么要将其限制为diskBlockSizeEstimate ...或者如果您执行想要将其作为每次读取的最大量,只需创建具有该大小的缓冲区即可。