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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| package snippet;
import org.apache.commons.io.FileUtils;
import java.io.*; import java.nio.channels.FileChannel; import java.nio.file.Files;
public class CopyFilesExample {
public static void main(String[] args) throws InterruptedException, IOException {
File source = new File("F:\\INSTALL_HISTORY\\ideaIU-2019.1.1.exe"); File dest = new File("F:\\TEST\\ideaIU-2019.1.1_1.exe");
long start = System.nanoTime(); long end; copyFileUsingFileStreams(source, dest); System.out.printf("%-50s = %20d\n", "Time taken by FileStreams Copy", (System.nanoTime() - start));
dest = new File("F:\\TEST\\ideaIU-2019.1.1_2.exe"); start = System.nanoTime(); copyFileUsingFileChannels(source, dest); end = System.nanoTime(); System.out.printf("%-50s = %20d\n", "Time taken by FileChannels Copy", (System.nanoTime() - start));
dest = new File("F:\\TEST\\ideaIU-2019.1.1_3.exe"); start = System.nanoTime(); copyFileUsingJava7Files(source, dest); end = System.nanoTime(); System.out.printf("%-50s = %20d\n", "Time taken by Java7 Files Copy", (System.nanoTime() - start));
dest = new File("F:\\TEST\\ideaIU-2019.1.1_4.exe"); start = System.nanoTime(); copyFileUsingApacheCommonsIO(source, dest); end = System.nanoTime(); System.out.printf("%-50s = %20d\n", "Time taken by Apache Commons IO Copy", (System.nanoTime() - start));
}
private static void copyFileUsingFileStreams(File source, File dest) throws IOException { InputStream input = null; OutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(dest); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buf)) > 0) { output.write(buf, 0, bytesRead); } } finally { input.close(); output.close(); } }
private static void copyFileUsingFileChannels(File source, File dest) throws IOException { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(source).getChannel(); outputChannel = new FileOutputStream(dest).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } finally { inputChannel.close(); outputChannel.close(); } }
private static void copyFileUsingJava7Files(File source, File dest) throws IOException { Files.copy(source.toPath(), dest.toPath()); }
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException { FileUtils.copyFile(source, dest); }
}
|