Java 读取流的IO差异
Java IO difference in reading streams
你能帮我弄清楚流吗?为什么在教程中我发现当从文件中读取时,我们使用 len != -1(例如)。而当从流中读取然后写入流时,我们使用 len> 0.What 是不同的什么时候读书?
PS 以下代码取自示例
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
你也可以看看IOUtils.copy和Files.copy他们也有区别
UPD 3
我看read方法不return0,或者可用字节数,或者-1。谢谢大家
没有区别。 InputStream.read(byte[])
的 javadoc 表示如下:
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.
和
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.
仔细阅读以上内容会告诉我们,如果缓冲区大小为零,read
只会 return 为零。
您的两个示例中的缓冲区大小不为零。因此 len != -1
和 length > 0
将具有相同的效果。
你能帮我弄清楚流吗?为什么在教程中我发现当从文件中读取时,我们使用 len != -1(例如)。而当从流中读取然后写入流时,我们使用 len> 0.What 是不同的什么时候读书?
PS 以下代码取自示例
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
你也可以看看IOUtils.copy和Files.copy他们也有区别
UPD 3
我看read方法不return0,或者可用字节数,或者-1。谢谢大家
没有区别。 InputStream.read(byte[])
的 javadoc 表示如下:
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.
和
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.
仔细阅读以上内容会告诉我们,如果缓冲区大小为零,read
只会 return 为零。
您的两个示例中的缓冲区大小不为零。因此 len != -1
和 length > 0
将具有相同的效果。