Programming Tips - Java: Best way to copy a binary file in Java

Date: 2016mar19 Update: 2025sep18 Language: Java Q. Java: Best way to copy a binary file in Java A. Use Java7+'s Files.copy() As shown in this full example:
import java.io.IOException; import java.io.File; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; class Demo { static boolean copyBinaryFile(final String srcFile, final String destFile) { File source = new File(srcFile); File dest = new File(destFile); try { Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch(IOException ex) { // Log the error? return false; } return true; } public static void main(String []args) { final boolean result = copyBinaryFile("/var/log/wtmp", "/tmp/wtmp_copy"); System.out.println("copy result=" + result); } }
Output:
copy result=true
Or if you want to percolate the exceptions:
static void copyBinaryFile(final String srcFile, final String destFile) throws IOException { File source = new File(srcFile); File dest = new File(destFile); Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING); }
There are other ways and I have seen articles comparing speeds. But this has these benefits: - Will profit from future improvements in Java - Very simple to use - Future proof