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

Comments

22 Feb 2010 - 2:23am by Anonymous (not verified)

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?

22 Feb 2010 - 6:47pm by patrick

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.

12 Mar 2010 - 7:08pm by Jooce (not verified)

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 be while ((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 addition if (len > 0) should be added before the line out.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.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.