Neat way to move a file in Java without nio
Saw this somewhere and figured I would post it before I lost it. Here is a very easy and simply way to move a file in Java without using the new-ish nio APIs.
File srcFile = new File(…some file to move…);
File destFile = new File(…where to move the file…);
srcFile.renameTo(destFile);
That’s it. Pretty simple. In fact it is actually shorter than the nio way of doing things
FileChannel in = new FileInputStream(source).getChannel();
FileChannel out = new FileOutputStream(target).getChannel();
in.transferTo(0, in.size(), out);
out.close();
in.close();
// Delete source file
Although I haven’t benchmarked them to see if there are any performance differences.
Update: I should have mentioned it when I wrote the original post but, as pointed out by Partha in the comments, there are a few gotchas with this method. As always check the documentation and test to make sure that it will work for your individual needs.