Skip to content

Instantly share code, notes, and snippets.

@donaldmunro
Forked from mrenouf/copyFile
Created June 20, 2012 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldmunro/2959131 to your computer and use it in GitHub Desktop.
Save donaldmunro/2959131 to your computer and use it in GitHub Desktop.
Efficient file copy in Java (pre-JDK7)
public static void copyFile(File sourceFile, File destFile, final boolean isOverwrite) throws IOException {
if (destFile.isDirectory())
destFile = new File(destFile, sourceFile.getName());
if (destFile.exists())
{
if (isOverwrite)
destFile.delete();
else
throw new IOException(destFile.getAbsolutePath() + " exists");
}
if (!destFile.exists()) {
destFile.createNewFile();
}
FileInputStream fIn = null;
FileOutputStream fOut = null;
FileChannel source = null;
FileChannel destination = null;
try {
fIn = new FileInputStream(sourceFile);
source = fIn.getChannel();
fOut = new FileOutputStream(destFile);
destination = fOut.getChannel();
long transfered = 0;
long bytes = source.size();
while (transfered < bytes) {
transfered += destination.transferFrom(source, 0, source.size());
destination.position(transfered);
}
} finally {
if (source != null) {
source.close();
} else if (fIn != null) {
fIn.close();
}
if (destination != null) {
destination.close();
} else if (fOut != null) {
fOut.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment