0

We are using filecopy in Java using similar code:

private void copyFileUsingFileChannels(File source, File dest) throws IOException {

    FileChannel inputChannel = null;
    FileChannel outputChannel = null;

    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

The problem is sometimes source and dest can point to the same file, in that case, the following statement, outputChannel = new FileOutputStream(dest).getChannel(); is causing the source to truncate to 0 bytes even if source is 400 kb till that point, as I think it is opening a stream for write with same handle. So what is the way to counter this?

Should I add something in my code saying

if (! (sourcec.getAbsolutePath().equalsIgnoreCase(destinationc.getAbsolutePath()))) 
    copyFiles(sourcec, destinationc);

Would the above work? Or is there a better way to handle this?

Thanks

gpgekko
  • 3,506
  • 3
  • 32
  • 35
garuda
  • 67
  • 1
  • 2
  • 8

1 Answers1

1

When you open a new FileOutputStream without append mode, you will truncate the file if it exists or create it if it doesn't. (Append mode wouldn't help you but wouldn't truncate the file) You want to avoid copying a file to itself, so I suggest you do the check you suggested, or use a strategies where you are not attempting to do this in the first place.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • yes makes sense, I will try to add a check similar to the above to avoid the filecopy all together if both absolute paths are equal. – garuda Feb 05 '14 at 08:21
  • 1
    +1 Note that this has nothing to do with Java. It is how most operating systems behave. – user207421 Feb 05 '14 at 08:54