Copying files from one directory to another in Java Copying files from one directory to another in Java java java

Copying files from one directory to another in Java


For now this should solve your problem

File source = new File("H:\\work-temp\\file");File dest = new File("H:\\work-temp\\file2");try {    FileUtils.copyDirectory(source, dest);} catch (IOException e) {    e.printStackTrace();}

FileUtils class from apache commons-io library, available since version 1.2.

Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.


There is no file copy method in the Standard API (yet). Your options are:

  • Write it yourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use FileChannel.transferTo()
  • User Apache Commons' FileUtils
  • Wait for NIO2 in Java 7


In Java 7, there is a standard method to copy files in java:

Files.copy.

It integrates with O/S native I/O for high performance.

See my A on Standard concise way to copy a file in Java? for a full description of usage.