Reputation: 1819
I need to copy an exact number of bytes from an InputStream to an OutputStream. One way to do it is to read one byte at a time and stop when the number is reached, but performance is not very good. If I use a byte array buffer to copy multiple bytes at a time, it is possible that a larger number of bytes would be read from the InputStream than the exact specified amount (if the desired amount if not divisible by the buffer size). The amount of data is quite large so I cannot just use a single byte array buffer and read all of the data into it.
Is there a way to copy an exact amount of data from one stream to another efficiently?
Any help would be appreciated!
Upvotes: 0
Views: 233
Reputation: 3513
This should work
int bytesToRead = ....
byte [] b = new byte[1024];
while (bytesToRead > 0)
{
int read = is.read(b, 0, Math.min(bytesToRead, 1024));
if (read < 0)
break;
bytesToRead -= read;
os.write(b, 0, read);
}
Upvotes: 1