Is there a standard Java library that handles common file operations such as moving/copying files/folders?
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.
java.io.File
can rename (move) files and folders. The classes in java.io
could be used to implement copy operations as well.
Check out: http://commons.apache.org/io/
It has copy, and as stated the JDK already has move.
Don't implement your own copy method. There are so many floating out there...
I'll just try to update this with java.nio operations, in case someone searches for this again:
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();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
Google's Guava library also has these:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html