Java – read from InputStream and write to OutputStream

This should be very simple. I searched Google, but I didn't see anyone mention the problems I noticed Everything I've seen is basically the same like this:

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

I know that read () returns - 1 when EOF is reached, but what if the file is smaller than the buffer or even the same size? For example, a 200 byte file is being read in I assume it reads 200 bytes, but returns - 1 This matches JavaDocs, but it also means that write () will never be called I wanted to actually tell me that it reads 200 bytes and returns - 1 at the next iteration

How can I solve this "problem"?

Solution

For reference only, guava has bytestreams Copy (InputStream, OutputStream), you can use it directly or see how it solves this problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>