LAST UPDATED: AUGUST 5, 2021
How to copy a file to another file in Java
In this post, we are going to learn to copy file data to another file. This is a general problem we face while working with files and input/output operations.
There are several ways by which we can copy data such as using FileInputStream
, FileOutputStream
, Files
classes. All these classes are used for file handling operations.
However, Files
class is easier to use because it provides copy()
method that instantly copy source file to destination file While in FileInputStream
, there is no copy method. So, we need to read the data first and write them to the destination file.
Here, we have some examples that illustrate the copy operations to the file. Below we have a file outfile.txt that contains some data and will be written to abc.txt file that is empty.
// File: outfile.txt
Welcome to Studytonight.com
It is technical portal.
Time for an Example
Let's create an example to copy a file to another file. Here, we are using copy()
method of Files
class that copy source to destination.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws IOException{
Path path = Paths.get("outfile.txt");
OutputStream os = new FileOutputStream("abc.txt");
Files.copy(path,os);
}
}
Time for another Example:
Let's take another example to copy a file to another file. Here, we are using FileInputStream
and FileOutputStream
to read and write data. By using the read()
method of FileInputStream class we read data from the source file and write data using write()
method of FileOutputStream.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException{
File source = new File("outfile.txt");
File dest = new File("abc.txt");
try{
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
}catch(Exception e) {
System.out.println(e);
}
}
}
After successful execution of the above code. You can see the abc.txt file that will have the same data as in the outfile.txt. That means data is copied successfuly.