How to copy a file in java?
Write a java program or function to copy a file. Your program should take two files as input – one is source file and another one is destination file and copy all the contents of source file to destination file.
The steps to copy a file are,
Step 1 : Create two File objects – sourceFile and destFile.
File sourceFile = new File(“Pass the source file location here”)
File destFile = new File(“Pass the destination file location here”)
Step 2 : Create FileInputStream object to read the content of sourceFile in bytes.
FileInputStream inStream = new FileInputStream(sourceFile)
Step 3 : Create FileOutputStream object to write the content to destFile.
FileInputStream outStream = new FileOutputStream(destFile)
Step 4 : Create one byte array called buffer with length of 1024.
byte buffer = new byte
Step 5 : Till the end of inStream, read the 1024 bytes of data into buffer array and write the same data into outStream.
while ((length = inStream.read(buffer)) != -1)
outStream.write(buffer, 0, length);
Step 6 : Close the resources.
There are 4 ways to copy a file in Java
- Java Copy File – Stream
This is the conventional way of file copy in java, here we create two Files, source and destination. Then we create InputStream from source and write it to destination file using OutputStream for java copy file operation.
Java Copy File – java.nio.channels.FileChannel
Java NIO classes were introduced in Java 1.4 and FileChannel can be used to copy file in java. According to transferFrom() method javadoc, this way of copy file is supposed to be faster than using Streams for java copy files.
Java Copy File – Apache Commons IO FileUtils
Apache Commons IO FileUtils.copyFile(File srcFile, File destFile) can be used to copy file in java. If you are already using Apache Commons IO in your project, it makes sense to use this for code simplicity. Internally it uses Java NIO FileChannel, so you can avoid this wrapper method if you are not already using it for other functions.
Java Copy File – Files class
If you are working on Java 7 or higher, you can use Files class copy() method to copy file in java. It uses File System providers to copy the files.