【发布时间】:2020-12-05 19:41:30
【问题描述】:
你能帮我弄清楚流吗?为什么在教程中我发现从文件读取时,我们使用 len != -1 (例如)。而从流中读取然后写入流时,我们使用 len> 0。读取时有什么区别?
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 方法不返回 0,或可用的字节数,或 -1。谢谢大家
【问题讨论】:
-
没有区别。
-
read方法在文件末尾返回-1,但是第二种情况,如果返回0给我们,那么我们就读完了
-
感谢源链接。最好编辑问题并将其包含在其中。
标签: java io stream inputstream