Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java IO to copy one File to another

Tags:

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

like image 284
Aly Avatar asked Mar 26 '10 00:03

Aly


People also ask

How do I copy a file in Java?

If you are working on Java 7 or higher, you can use Files class copy() method to copy file in java. It uses File System providers to copy the files.

How do I copy a file to another file?

Right-click and pick Copy, or press Ctrl + C . Navigate to another folder, where you want to put the copy of the file. Click the menu button and pick Paste to finish copying the file, or press Ctrl + V . There will now be a copy of the file in the original folder and the other folder.

What is copy () in Java?

The copy() method of Java Collections class copies all of the elements from one list into another list. In this method, the size of the destination list must be greater than or equal to the size of the source list.

How do I move a file from one directory to another in Java 8?

You can move a file or directory by using the move(Path, Path, CopyOption...) method. The move fails if the target file exists, unless the REPLACE_EXISTING option is specified. Empty directories can be moved.


2 Answers

If you want to be lazy and get away with writing minimal code use

FileUtils.copyFile(src, dest)

from Apache IOCommons

like image 29
Maddy Avatar answered Oct 20 '22 16:10

Maddy


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.

like image 86
João Silva Avatar answered Oct 20 '22 15:10

João Silva