1. Copy FileStreams
This is the most classic way to copy the contents of one file to another file. Using the read file A byte FileInputStream, FileOutputStream written to a file using B. This is the code for the first method:
1 private static void copyFileUsingFileStreams(File source, File dest) 2 throws IOException { 3 InputStream input = null; 4 OutputStream output = null; 5 try { 6 input = new FileInputStream(source); 7 output = new FileOutputStream(dest); 8 byte[] buf = new byte[1024]; 9 int bytesRead; 10 while ((bytesRead = input.read(buf)) > 0) { 11 output.write(buf, 0, bytesRead); 12 } 13 } finally { 14 input.close(); 15 output.close(); 16 } 17
2. Copy FileChannel
1 private static void copyFileUsingFileChannels(File source, File dest) throws IOException { 2 FileChannel inputChannel = null; 3 FileChannel outputChannel = null; 4 try { 5 inputChannel = new FileInputStream(source).getChannel(); 6 outputChannel = new FileOutputStream(dest).getChannel(); 7 outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); 8 } finally { 9 inputChannel.close(); 10 outputChannel.close(); 11 } 12 }
3. Using Commons IO Copy
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { FileUtils.copyFile(source, dest); }
4. Class Files Replication of Java7
private static void copyFileUsingJava7Files(File source, File dest) throws IOException { Files.copy(source.toPath(), dest.toPath()); }