1

The read() method inside copyFile() reads buf.length bytes from the input stream and then it writes them to the output stream from the start until len.

public static boolean copyFile(InputStream inputStream, OutputStream out) {
    byte buf[] = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buf)) != -1) {
            out.write(buf, 0, len);

        }
        out.close();
        inputStream.close();
    } catch (IOException e) {
        return false;
    }
    return true;
}

If we always writing to the output stream from the start isn't the data of the previous iteration overwritten?

Don't we need to keep track of the offset? For example if the first iteration wrote 1024 bytes then the second iteration should write out.write(buf,1024,len);.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Themelis
  • 4,048
  • 2
  • 21
  • 45
  • 2
    The start is the start of the array, not of the stream. The data is in fact appended to the previous one each time. – Arnaud Nov 22 '18 at 13:09

2 Answers2

0

The fact is that the buf is a buffer and not the entire data stream.

Also, you are using public int read(byte[] b) method which means which it is same as read(b, 0, b.length). So the buffer shall be pointing to next buf.length values of the data.

For more information, please check https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read(byte[]) .

CS_noob
  • 557
  • 1
  • 6
  • 18
  • Thanks for your answer. My query was about write() but it's ok it's being answered in the comments. – Themelis Nov 22 '18 at 13:14
0

As @Arnaud commented

The start is the start of the array, not of the stream. The data is in fact appended to the previous one each time.

I was not careful quick scanning the docs and from "Writes len bytes from the specified byte array starting at offset off to this output stream", I got the point that off was the offset of the stream.

Themelis
  • 4,048
  • 2
  • 21
  • 45