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

Date: 2016mar19 Language: Java Q. Java: Best way to copy a binary file in Java A. Use Java7+'s Files.copy()
import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; 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; }
Or if you want to percolate the exceptions:
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