Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy and rename file on different location

Tags:

java

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?

like image 867
Damir Avatar asked Mar 22 '11 07:03

Damir


2 Answers

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

like image 188
jmj Avatar answered Nov 14 '22 06:11

jmj


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();
      }
    }
 }
like image 28
Dead Programmer Avatar answered Nov 14 '22 06:11

Dead Programmer