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