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
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.
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.
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.
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.
If you want to be lazy and get away with writing minimal code use
FileUtils.copyFile(src, dest)
from Apache IOCommons
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With