-
-
Save donaldmunro/2959131 to your computer and use it in GitHub Desktop.
Efficient file copy in Java (pre-JDK7)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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