Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move / Copy File Operations in Java

Tags:

java

file

copy

move

Is there a standard Java library that handles common file operations such as moving/copying files/folders?

like image 700
MSumulong Avatar asked Nov 18 '08 23:11

MSumulong


People also ask

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

We can use Files. move() API to move file from one directory to another.


2 Answers

Here's how to do this with java.nio operations:

public static void copyFile(File sourceFile, File destFile) throws IOException {     if(!destFile.exists()) {         destFile.createNewFile();     }      FileChannel source = null;     FileChannel destination = null;     try {         source = new FileInputStream(sourceFile).getChannel();         destination = new FileOutputStream(destFile).getChannel();          // previous code: destination.transferFrom(source, 0, source.size());         // to avoid infinite loops, should be:         long count = 0;         long size = source.size();                       while((count += destination.transferFrom(source, count, size-count))<size);     }     finally {         if(source != null) {             source.close();         }         if(destination != null) {             destination.close();         }     } } 
like image 182
Rigo Vides Avatar answered Sep 22 '22 06:09

Rigo Vides


Not yet, but the New NIO (JSR 203) will have support for these common operations.

In the meantime, there are a few things to keep in mind.

File.renameTo generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.

When a rename doesn't work you will need to actually copy the file (deleting the original with File.delete if it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferTo or FileChannel.transferFrom methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.

like image 27
erickson Avatar answered Sep 26 '22 06:09

erickson