How to Copy a File in Java

Copying a file is a common task that can be performed using various classes and methods in Java. This tutorial will demonstrate different ways to copy a file using standard Java I/O streams and the NIO (New I/O) package.

Table of Contents

  1. Introduction
  2. Using Java I/O Streams
    • FileInputStream and FileOutputStream
  3. Using Java NIO
    • Files.copy() Method
  4. Conclusion

Introduction

Copying a file involves reading data from the source file and writing it to the destination file. Java provides multiple ways to achieve this, including using traditional I/O streams and the NIO package introduced in Java 7, which provides more efficient and convenient methods for file operations.

Using Java I/O Streams

Using FileInputStream and FileOutputStream

The FileInputStream and FileOutputStream classes are used for reading and writing bytes. We can use these classes to copy a file byte by byte.

Example

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFileUsingIO {
    public static void main(String[] args) {
        String sourceFile = "source.txt";
        String destinationFile = "destination.txt";

        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(destinationFile)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("File copied successfully using FileInputStream and FileOutputStream.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • FileInputStream is used to read bytes from the source file.
  • FileOutputStream is used to write bytes to the destination file.
  • A buffer of 1024 bytes is used to read and write data in chunks, improving performance.
  • The while loop reads bytes from the source file and writes them to the destination file until the end of the file is reached.

Using Java NIO

Using Files.copy() Method

The NIO package provides a more efficient and convenient way to copy files using the Files.copy() method. This method is part of the java.nio.file.Files class and can be used to copy files with various options.

Example

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class CopyFileUsingNIO {
    public static void main(String[] args) {
        Path sourcePath = Paths.get("source.txt");
        Path destinationPath = Paths.get("destination.txt");

        try {
            Files.copy(sourcePath, destinationPath);
            System.out.println("File copied successfully using Files.copy().");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • Paths.get() is used to obtain the Path objects for the source and destination files.
  • Files.copy() is used to copy the file from the source path to the destination path.
  • This method provides a simple and efficient way to copy files with less code.

Copying with Overwrite Option

If you want to overwrite the destination file if it already exists, you can use the StandardCopyOption.REPLACE_EXISTING option.

Example

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.io.IOException;

public class CopyFileWithOverwrite {
    public static void main(String[] args) {
        Path sourcePath = Paths.get("source.txt");
        Path destinationPath = Paths.get("destination.txt");

        try {
            Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File copied successfully with overwrite option.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • StandardCopyOption.REPLACE_EXISTING is used to specify that the existing destination file should be overwritten if it exists.
  • The Files.copy() method copies the file from the source path to the destination path, overwriting the existing file if necessary.

Conclusion

Copying a file in Java can be accomplished using various methods, including traditional I/O streams and the NIO package. The FileInputStream and FileOutputStream classes provide a straightforward way to copy files byte by byte, while the NIO package's Files.copy() method offers a more efficient and convenient approach. By understanding these methods, you can choose the appropriate approach for copying files in your Java applications.

Comments