In this tutorial, we will cover how to copy any file in Java.
If you consider Java 6 or earlier, Java does not have an object or method that supports us copying a file, only creating or deleting a file.
So if you are working on a project that uses only Java 6, please refer to the following code if there is a need to copy a file:
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 |
package com.huongdanjava.javaexample; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Example { public static void main(String[] args) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream("F:/source.txt"); os = new FileOutputStream("E:/destination.txt"); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } } } |
If you are working with Java 7, copying a file does not have to be painful, because the Files object which was introduced in Java 7, can help us do this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.huongdanjava.javaexample; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class Example { public static void main(String[] args) throws IOException { File source = new File("F:/source.txt"); File dest = new File("E:/destination.txt"); Files.copy(source.toPath(), dest.toPath()); } } |
In addition, we have another way to use the FileUtils object in the Apache Commons IO library. This object contains many overload static copyFile() methods that allow us to copy a file easily. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.huongdanjava.javaexample; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class Example { public static void main(String[] args) throws IOException { File source = new File("F:/source.txt"); File dest = new File("E:/destination.txt"); FileUtils.copyFile(source, dest); } } |