Dave's Brain

Browse - Programming Tips - What's the best way to copy a binary file in Java?

Date: 2016mar19
Language: Java

Q.  What's the 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

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.