Different methods to copy a file in Java
File handling is very important part of any application. Java provides several classes and methods to ease this task. The reading and writing operations are done easily with the help of this classes and methods.
The list below shows five different ways in which we can copy a file in Java.
- Using
FileInputStream
andFileOutputStream
- Using
Paths
andFiles
- Using
RandomAccessFile
Class - Using
FileChannel
- Using
Files.copy()
Using FileInputStream and FileOutputStream
This is a traditional approach to copy a file in Java. Firstly, we will create source file and destination file. Thereafter, we create InputStream
from the source to read a file and write it to the destination file using OutputStream
.
Example : In this example, content of test.txt will be copied to output.txt
. Thereafter, we are reading the content of output file to verify the copy operation.
// Program to copy a file in Java
import java.io.*;
public class MyClass {
public static void main(String[] args) {
// Creating object of fileinputstream and fileoutputstream
FileInputStream fin = new FileInputStream("test.txt");
FileOutputStream fo = new FileOutputStream("output.txt");
int c;
// Reading file as a byte and writing to a output file
while ((c = fin.read()) != -1) {
fo.write(c);
}
System.out.println("File test.txt is copied successfully");
fin.close();
fo.close();
//Reading a file to verify if content was copied
System.out.println("-----Reading output file-----");
File file = new File("output.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Output
File test.txt is copied successfully
-----Reading output file-----
Hello world
Welcome to the world of Java Programming
Using Paths and Files Class
In this approach we are using Paths class and Files class of java.nio.file
package to copy a file. The Paths class consist of static methods that return a path by converting a path string to uri. Whereas, newInputStream
method of Files class opens a file returning an input stream to read from the file. The newOutputStream
method of Files class opens or creates a file returning an output stream that may be used to write bytes to the file.
Example : In this example, content of test.txt will be copied to output.txt. Thereafter, we are reading the content of output file to verify the copy operation.
// Program to copy a file in Java
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
var src = Paths.get("javademo/test.txt");
var dest = Paths.get("javademo/output.txt");
var fin = Files.newInputStream(src);
var fo = Files.newOutputStream(dest);
int c;
// Reading file as a byte and writing to a output file
while ((c = fin.read()) != -1) {
fo.write(c);
}
System.out.println("File test.txt is copied successfully");
fin.close();
fo.close();
//Reading a file to verify if content was copied
System.out.println("-----Reading output file-----");
File file = new File("output.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Output
File test.txt is copied successfully
-----Reading output file-----
Hello world
Welcome to the world of Java Programming
Using RandomAccessFile Class
In this approach, we are using RandomAccessFile
class of java.io package to copy a file. Here, it creates a random access file stream to read from, and optionally to write to, a file with the specified name. Thereafter, we are using read and write method to read from and write to a file respectively.
Example :In this example, content of test.txt
will be copied to output.txt
. Thereafter, we are reading the content of output file to verify the copy operation.
// Program to copy a file in Java
import java.io.RandomAccessFile;
import java.io.*;
public class MyClass {
public static void main(String[] args) throws IOException {
RandomAccessFile src = new RandomAccessFile("test.txt", "r");
RandomAccessFile dest = new RandomAccessFile("output.txt", "rw");
int c;
// Reading file as a byte and writing to a output file
while ((c = src.read()) != -1) {
dest.write(c);
}
System.out.println("File test.txt is copied successfully");
//Reading a file to verify if content was copied
System.out.println("-----Reading output file-----");
File file = new File("output.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Output
File test.txt is copied successfully
-----Reading output file-----
Java: write once, run away! –Brucee
If Java had true garbage collection, most programs would delete themselves upon execution. – Robert Sewell
Measuring programming progress by lines of code is like measuring aircraft building progress by weight. – Bill Gates
Using FileChannel Class
In this approach, we are using FileChannel
Class of java.nio.channels
package to copy a file. Here, we are creating a channel that cna be used for reading, writing, mapping and manipulating a file. Here, transferFrom
method transfers bytes into this channel's file from the given readable byte channel. Alternatively, we can also use transferTo
method to copy a file.
Example : In this example, content of test.txt will be copied to output.txt. Thereafter, we are reading the content of output file to verify the copy operation.
// Program to copy a file in Java
import java.nio.channels.FileChannel;
import java.io.*;
public class MyClass {
public static void main(String[] args) throws IOException {
FileChannel sf = new FileInputStream("test.txt").getChannel();
FileChannel df = new FileOutputStream("output.txt").getChannel();
df.transferFrom(sf, 0, sf.size());
System.out.println("File test.txt is copied successfully");
//Reading a file to verify if content was copied
System.out.println("-----Reading output file-----");
File file = new File("output.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Output
File test.txt is copied successfully
-----Reading output file-----
Java: write once, run away! –Brucee
If Java had true garbage collection, most programs would delete themselves upon execution. – Robert Sewell
Measuring programming progress by lines of code is like measuring aircraft building progress by weight. – Bill Gates
Using Files.copy()
In this approach, we are using copy method of Files class of java.nio.file
package to copy a file. Note that if output file is existing it will throw a FileAlreadyExists
exception.
Example : In this example, content of test.txt will be copied to output.txt. Thereafter, we are reading the content of output file to verify the copy operation.
// Program to copy a file in Java
import java.nio.file.Files;
import java.io.*;
public class MyClass {
public static void main(String[] args) throws IOException {
File sf = new File("test.txt");
File df = new File("output.txt");
Files.copy(sf.toPath(), df.toPath());
System.out.println("File test.txt is copied successfully");
//Reading a file to verify if content was copied
System.out.println("-----Reading output file-----");
File file = new File("output.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
Output
File test.txt is copied successfully
-----Reading output file-----
Java: write once, run away! –Brucee
If Java had true garbage collection, most programs would delete themselves upon execution. – Robert Sewell
Measuring programming progress by lines of code is like measuring aircraft building progress by weight. – Bill Gates
Summary
The knowledge of copying a file in Java is very useful while working on real time applications. In this tutorial, we covered five different approaches to copy a file in Java. As per the requirement of an application, we can choose an appropriate approach for copying. We learned in detail about this approaches with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on copying a file in Java.
References
FileInputStream Class
FileOutputStream Class
Paths Class
Files Class
RandomAccessFile Class
FileChannel Class