Copy and rename file on different location

Why to reinvent the wheel, just use FileUtils.copyFile(File srcFile, File destFile) , this will handle many scenarios for you


There is Files class in package java.nio.file. You can use the copy method.

Example: Files.copy(sourcePath, targetPath).

Create a targetPath object (which is an instance of Path) with the new name of your file.


I would suggest Apache commons FileUtils or NIO (direct OS calls)

or Just this

Credits to Josh - standard-concise-way-to-copy-a-file-in-java


File source=new File("example.tar.gz");
File destination=new File("/temp/example_test.tar.gz");

copyFile(source,destination);

Updates:

Changed to transferTo from @bestss

 public static void copyFile(File sourceFile, File destFile) throws IOException {
     if(!destFile.exists()) {
      destFile.createNewFile();
     }

     FileChannel source = null;
     FileChannel destination = null;
     try {
      source = new RandomAccessFile(sourceFile,"rw").getChannel();
      destination = new RandomAccessFile(destFile,"rw").getChannel();

      long position = 0;
      long count    = source.size();

      source.transferTo(position, count, destination);
     }
     finally {
      if(source != null) {
       source.close();
      }
      if(destination != null) {
       destination.close();
      }
    }
 }

Tags:

Java