habib
habib

Reputation: 91

copy a text file in java

here is a code that copy a text file I have some questions about that:

 public class CopyFile {

    public static void main(String[] args) {
        File f1 = new File("loremipsum.txt");
        File f2 = new File("target.txt");

        InputStream in = new FileInputStream(f1);
        OutputStream out = new FileOutputStream(f2);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    }
}

I know it is not completed yet,I have a question in this part of it:

    while ((len = in.read(buf))> 0){
        out.write(buf,0,len);

    }

I want know in this part ,at first (len = in.read(buf))> 0 executed and read the all bytes of the array then stores it's length in the len variable,
Or it is read the first byte buf[0] and store 1 in the len variable and because it's >0 then this part of code out.write(buf,0,len); executed and again (len = in.read(buf))> 0 and... .

Upvotes: 0

Views: 372

Answers (2)

DavidPostill
DavidPostill

Reputation: 7921

From the documentation read(byte[] b):

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown.

If the length of b 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.

The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.

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.

Upvotes: 1

Smutje
Smutje

Reputation: 18123

(len = in.read(buf))> 0

Does three things:

  1. Read from in and stores the result in buf.
  2. Stores the length of the read content in len.
  3. Compares the read length with 0 to determine whether in has returned content or reading is finished.

Upvotes: 0

Related Questions