java这个简单的复制程序是如何工作的
我应该编写一个类似于Unix cp命令的程序。我找到了这段代码,但无法真正理解它是如何工作的
FileInputStream in = new FileInputStream(args[0]);
FileOutputStream out = new FileOutputStream(args[1]);
byte[] buf = new byte[1024];
int i = 0;
while ((i = in.read(buf)) != -1) {
out.write(buf, 0, i);
}
while循环是如何工作的?我假设它从InputStream中读取1024字节的部分,将它们保存到字节数组buf,然后将buf写入新文件
但是什么呢
in.read(buf);
分配给我?while如何在整个文件中循环(是什么告诉in.read(buf)读取下一个1024字节的数据,而不是一遍又一遍地读取前1024字节的数据)
谢谢, P
# 1 楼答案
让我们一步一步走,好吗
前四行并不难。创建输入和输出流。分配大小为1024的缓冲区
下一步是while循环。首先要执行的是:
这将尽可能多地读入缓冲区,
buf
,然后返回读取的字节。然后将其分配给i
,因此i
是buf
中来自流的字节数请注意
read()
调用将推进流。这意味着它不会重复字节。因此,如果您的流是:你可以读进来
返回
2
(读入的数字)。这条溪流现在是:回到循环!从流中读入后,我们检查是否有任何内容读入
buf
注意
计算值为
i
,因此循环条件为while (i != -1)
。此语句如此计算的原因与我们可以执行的原因类似:这实际上是:
下一行很简单。将
buf
中的所有字节从0
写入i
最后,这个循环可以重写为:
# 2 楼答案
返回读入buf的字节数。如果之前已到达文件结尾,则返回-1
资料来源:http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read()
文件有一个指针,每次访问(读/写)都会移动该指针,因此下一次读/写将从上一次读/写结束的位置开始
# 3 楼答案
while循环正在检查是否仍有数据要读取,并且正在为
i
分配已读取的字节数。然后使用它将正确的字节数写入输出流# 4 楼答案
相当于: