10

I have one file example.tar.gz and I need to copy it to another location with different name example _test.tar.gz. I have tried with

private void copyFile(File srcFile, File destFile) throws IOException {

    InputStream oInStream = new FileInputStream(srcFile);
    OutputStream oOutStream = new FileOutputStream(destFile);

    // Transfer bytes from in to out
    byte[] oBytes = new byte[1024];
    int nLength;

    BufferedInputStream oBuffInputStream = new BufferedInputStream(oInStream);
    while((nLength = oBuffInputStream.read(oBytes)) > 0) {
        oOutStream.write(oBytes, 0, nLength);
    }
    oInStream.close();
    oOutStream.close();
}

where

String from_path = new File("example.tar.gz");
File source = new File(from_path);

File destination = new File("/temp/example_test.tar.gz");
if(!destination.exists())
    destination.createNewFile();

and then

copyFile(source, destination);

It doesn't work. The path is correct. It prints that the file exists. Can anybody help me?

Mionutm
  • 58
  • 4
Damir
  • 54,277
  • 94
  • 246
  • 365

3 Answers3

42

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

Matt
  • 74,352
  • 26
  • 153
  • 180
jmj
  • 237,923
  • 42
  • 401
  • 438
8
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();
      }
    }
 }
Community
  • 1
  • 1
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112
  • Using FileStreams might be inefficient to copy files, look at `java.nio.channels.FileChannel.transferTo` – bestsss Mar 22 '11 at 07:59
2

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.

The_Cute_Hedgehog
  • 1,280
  • 13
  • 22