How to copy file in Java from one directory to another is common requirement. Java didn’t come with any ready made code to copy file. Below method is the Fastest Way
to Copy File in Java?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package com.crunchify.tutorials; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; /** * @author Crunchify.com */ public class CrunchifyFileCopy { public static void main(String[] args) { File file1 =new File("/Users/<username>/Documents/file1.txt"); File file2 =new File("/Users/<username>/Documents/file2.txt"); try { fileCopy(file1, file2); } catch (IOException e) { e.printStackTrace(); } } // Fastest way to Copy file in Java @SuppressWarnings("resource") public static void fileCopy( File in, File out ) throws IOException { FileChannel inChannel = new FileInputStream( in ).getChannel(); FileChannel outChannel = new FileOutputStream( out ).getChannel(); try { // Try to change this but this is the number I tried.. for Windows, 64Mb - 32Kb) int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while ( position < size ) { position += inChannel.transferTo( position, maxCount, outChannel ); } System.out.println("File Successfully Copied.."); } finally { if ( inChannel != null ) { inChannel.close(); } if ( outChannel != null ) { outChannel.close(); } } } } |
There is another Traditional Way to perform the same operation and you can get code from here: https://crunchify.com/java-file-copy-example-simple-way-to-copy-file-in-java/