Copy Files Using Java Files Class

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to copy a file to another file in Java. There are several ways to copy a file, such as using FileInputStream, FileOutputStream, and the Files class. Here, we will focus on the Files class, which is easier to use because it provides a copy() method that instantly copies the source file to the destination file.

Import required libraries

In the new Java file, import the required libraries using the following code:

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;
import java.io.File;
import java.io.FileInputStream;

Create a file object

Create a file object that points to the source file that needs to be copied.

File source = new File("sourceFile.txt");

Create a destination file object

Create a destination file object that points to the file where you want to copy the data from the source file.

File destination = new File("destinationFile.txt");

Use the Files class to copy the data

Use the Files class to copy the data from the source file to the destination file. You can use the copy() method of the Files class to do this.

Path sourcePath = Paths.get(source.getAbsolutePath());
OutputStream destinationStream = new FileOutputStream(destination);
Files.copy(sourcePath, destinationStream);

Use FileInputStream and FileOutputStream to copy the data

In this method, we will use FileInputStream and FileOutputStream to copy the data. Use the following code to read data from the source file and write data using the write() method of the FileOutputStream.

FileInputStream sourceStream = new FileInputStream(source);
FileOutputStream destinationStream = new FileOutputStream(destination);

byte[] buffer = new byte[1024];
int bytesRead;

while ((bytesRead = sourceStream.read(buffer)) > 0) {
    destinationStream.write(buffer, 0, bytesRead);
}

sourceStream.close();
destinationStream.close();

Compile the program

Open a terminal and navigate to the directory ~/project. Compile the program using the following command:

javac CopyFile.java

Execute the program

Run the program using the following command:

java CopyFile

Summary

In this lab, you learned how to copy data from one file to another file using the Files class and FileInputStream and FileOutputStream. The Files class is easier to use because it provides a copy() method that copies data instantly. You can use the FileInputStream and FileOutputStream to copy the data by reading and writing it manually.

Other Java Tutorials you may like