There are many ways in which you can copy file in java.
Example : Copy File in java using InputStream/OutStream
In the first example we will see the traditional way of copying file using the InputStream/OutStream. This is the method used prior to jdk 7
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 |
package com.kscodes.sampleproject; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileCopyExample { /** * @param args */ public static void main(String[] args) throws IOException { copyFile(); } public static void copyFile() throws IOException { File sourceFile = new File("C:\\sourceFile.txt"); File destinationFile = new File("C:\\destinationFile.txt"); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(sourceFile); output = new FileOutputStream(destinationFile); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buf)) > 0) { output.write(buf, 0, bytesRead); } System.out.println("File copied !!!"); } finally { input.close(); output.close(); } } } |
Example : Copy File in java using InputStream/OutStream
In this example we will use the JDK7 Files.copy feature. This is easy to use and we have to worry less about closing the streams that were opened as done in above example.
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 |
package com.kscodes.sampleproject; import java.io.File; import java.nio.file.Files; public class FileCopyExample { /** * @param args */ public static void main(String[] args) throws IOException { copyFileJava7Style(); } public static void copyFileJava7Style() throws IOException { File sourceFile = new File("C:\\sourceFile.txt"); File destinationFile = new File("C:\\destinationFile.txt"); Files.copy(sourceFile.toPath(), destinationFile.toPath()); System.out.println("Java 7 makes File Copy easy .. File copied !!!"); } } |
You can get more details on the Files API on the JDK documentation HERE