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.

2 thoughts on “Neat way to move a file in Java without nio

  1. Partha

    The renameTo method has a severe caveat. Checkout the javadoc at: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#renameTo(java.io.File)

    All the “might be”s actually happen. Especially moving files between different partitions may bite you most unexpectedly. One solution is to use commons-io package. That has some sweet stuff in there 🙂

    • Tyler Burton

      Thank you Partha. I had forgotten to mention the limitations of this approach and have updated the post.

Comments are closed.