有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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


共 (4) 个答案

  1. # 1 楼答案

    让我们一步一步走,好吗

    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);
    }
    

    前四行并不难。创建输入和输出流。分配大小为1024的缓冲区

    下一步是while循环。首先要执行的是:

    (i = in.read(buf))
    

    这将尽可能多地读入缓冲区,buf,然后返回读取的字节。然后将其分配给i,因此ibuf中来自流的字节数

    请注意read()调用将推进流。这意味着它不会重复字节。因此,如果您的流是:

    1 51 23 10 6 73
    

    你可以读进来

    1 51
    

    返回2(读入的数字)。这条溪流现在是:

    23 10 6 73
    

    回到循环!从流中读入后,我们检查是否有任何内容读入buf

    ... != -1
    

    注意

    (i = in.read(buf))
    

    计算值为i,因此循环条件为while (i != -1)。此语句如此计算的原因与我们可以执行的原因类似:

    a = b = 1;
    

    这实际上是:

    a = (b = 1);
    

    下一行很简单。将buf中的所有字节从0写入i

    最后,这个循环可以重写为:

    while(true){
        int i = in.read(buf);
        if(i == -1)
            break;
        out.write(buf, 0, i);
    }
    
  2. # 3 楼答案

    public int read(byte[] b) throws IOException
    

    Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

    Returns the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

    while循环正在检查是否仍有数据要读取,并且正在为i分配已读取的字节数。然后使用它将正确的字节数写入输出流

    pubilc void write(byte[] b, int off, int len) throws IOException
    

    Writes len bytes from the specified byte array starting at offset off to this file output stream.

  3. # 4 楼答案

    And how does the while loop through the whole file(what tells in.read(buf) to read the next 1024 bytes of data and not the same first 1024 over and over)?

    while ((i = in.read()) != -1) {
                out.write(buf, 0, i);
    }
    

    相当于:

    i = in.read();
    while (i != -1) {
            out.write(buf, 0, i);
            i = in.read();
    }