Copy a file (optionally marking as temporary)
9
Copy a file to a new location, optionally marking the file as a temporary file (to be deleted on application exit).
Note there are issues for temporary files - not all the parent directories that might be created are guaranteed to be deleted - only the immediate parent directory will be deleted on exit if created. Other higher-level directories will not be deleted, even if the file is marked as temporary.
Note there are issues for temporary files - not all the parent directories that might be created are guaranteed to be deleted - only the immediate parent directory will be deleted on exit if created. Other higher-level directories will not be deleted, even if the file is marked as temporary.
/**
* Copy a file to a new location
* @param _srcFilename The original file
* @param _destFilename The location where a copy should be created
* @param _tmpFile If true, the created file copy will be deleted on program exit
* @throws IOException If there are IO problems during the copy
*/
public static void copyFile(String _srcFilename, String _destFilename, boolean _tmpFile) throws IOException {
// Create channel on the source
FileChannel srcChannel = new FileInputStream(_srcFilename).getChannel();
// Create destination file and associated directories if required
File destFile = new File(_destFilename);
if(_tmpFile) {
destFile.deleteOnExit();
}
File destDir = destFile.getParentFile();
if (destDir != null && !destDir.exists()) {
destDir.mkdirs();
if (_tmpFile) {
destDir.deleteOnExit();
}
}
destFile.createNewFile();
// Create channel on the destination
FileChannel dstChannel = new FileOutputStream(_destFilename).getChannel();
// Copy entirefile contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
// Close the channels
srcChannel.close();
dstChannel.close();
}






There are currently no comments for this snippet.