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