我通過套接字發送文件,並試圖將它寫入接收器的文件。從InputStream複製到BufferedOutputStream
我見過的例子是做這樣的事情:
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時,會引發異常。我一定要執行,說的邏輯:「如果(bytesRead == - 1)設置bytesToRead =檔案大小 - 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;
}
}
而且,它會更好,而(totalBytesRead =檔案大小做! )而不是while(bytesRead!= -1)?
如果您正在複製內存塊,則不需要緩衝流。緩衝是爲了將較小的讀取/寫入轉變爲較大的讀取/寫入。 –