Copying One File to Another
This example uses file streams to copy the contents of one
file to another file. See Copying One File to Another for an example
that uses file channels.
// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
First thought... this website could be the best thing since sliced bread. Second thought is, why make the array 1024? Can you do it one byte at a time? I want to make sure that the files are forensically equal meaning their hash code would stay the same. Does this do that?
The array is 1024 for performance reasons. Setting it to 1 would make no difference to the contents of the target copy. Perhaps you're concerned that the routine will pad the file with extra bytes. This won't happen because the in.read(buf) will return the number of bytes read and the out.write() will only write out that many bytes from the buffer.
I encountered some problems with this code. It does not always produce exact file copies. Sometimes a few bytes are missing. After a little research I found out that this source code contains two errors. First, the statement
while ((len = in.read(buf)) > 0)should bewhile ((len = in.read(buf)) >= 0), because FileInputStream's read method can actually return 0 as a regular value. This can be the case, e.g. when the stream's internal buffer is underrun while accessing a large file over the network. So, in additionif (len > 0)should be added before the lineout.write(buf, 0, len);. Second error: an invocation of FileOutputStream's flush method is missing. It should be called directly after the while loop before closing the streams to ensure that the output stream is fully written to disk. Tested with JDK 1.6.0_18.