英文:
Java IO difference in reading streams
问题
以下是您要求的翻译内容:
"Could you help me figure out the streams. Why in the tutorials I find that when reading from a file, we use len != -1 (for example). And when reading from a stream and then writing to a stream, we use len > 0. What is the difference when reading?
PS The codes below are taken from examples
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
byte[] buf = new byte[8192];
int length;
while ((length = source.read(buf)) > 0) {
target.write(buf, 0, length);
}
}
UPD
UPD 2
You can also look at IOUtils.copy and Files.copy. They are different too.
UPD 3
I read that the read method does not return 0, or the available number of bytes, or -1. Thanks everyone"
英文:
Could you help me figure out the streams. Why in the tutorials I find that when reading from a file, we use len != -1 (for example).And when reading from a stream and then writing to a stream, we use len> 0.What is the difference when reading?
PS The codes below are taken from examples
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
byte[] buf = new byte[8192];
int length;
while ((length = source.read(buf)) > 0) {
target.write(buf, 0, length);
}
}
UPD
UPD 2
You can also look at IOUtils.copy and Files.copy They are different too
UPD 3
I read that the read method does not return 0, or the available number of bytes, or -1. Thanks everyone
答案1
得分: 3
以下是翻译好的部分:
没有区别。InputStream.read(byte[])
的 javadoc 描述如下:
> 如果[缓冲区]的长度为零,则不会读取任何字节,并返回0;否则,将尝试读取至少一个字节。如果由于流位于文件末尾而没有字节可用,则返回值-1;否则,将读取至少一个字节并存储到 b 中。
和
> 返回读取到缓冲区的总字节数,如果没有更多数据因为已经到达流的末尾,则返回-1。
仔细阅读上述内容告诉我们,只有当缓冲区大小为零时,read
才会返回零。
在您的两个示例中,缓冲区大小不为零。因此 len != -1
和 length > 0
将具有相同的效果。
英文:
There is no difference. The javadoc for InputStream.read(byte[])
says the following:
> If the length of [the buffer] is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b.
and
> Returns the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
A careful reading of the above tells us that read
will only ever return zero if the buffer size is zero.
The buffer size is not zero in your two examples. Therefore len != -1
and length > 0
will have the same effect.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论