Aly Aly - 5 months ago 5x
Java Question

java IO to copy one File to another

I have two 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


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.