java IO to copy one File to another

Aly picture Aly · Mar 26, 2010 · Viewed 53.5k times · Source

I have two Java.io.File objects file1 and file2. I want to copy the contents from file1 to file2. Is there an standard way to do this without me having to create a method that reads file1 and write to file2

Answer

João Silva picture João Silva · Mar 26, 2010

No, there is no built-in method to do that. The closest to what you want to accomplish is the transferFrom method from FileOutputStream, like so:

  FileChannel src = new FileInputStream(file1).getChannel();
  FileChannel dest = new FileOutputStream(file2).getChannel();
  dest.transferFrom(src, 0, src.size());

And don't forget to handle exceptions and close everything in a finally block.