File Copy
## Java File Copy: How to Copy File Contents in Java
In Java development, copying the contents of one file to another is a fundamental I/O operation. Depending on your Java version and performance requirements, there are several ways to achieve this.
This tutorial demonstrates how to copy files using traditional stream-based methods (as shown in the classic example) and modern, more efficient alternatives introduced in newer Java versions.
---
## 1. Traditional Stream-Based File Copy (Classic Approach)
The classic way to copy files in Java is by using `FileInputStream` and `FileOutputStream` with a byte buffer. This method is highly compatible and works across all Java versions.
### Code Example
The following program writes a string to a source file (`srcfile`), copies its contents to a destination file (`destnfile`) using a byte buffer, and then reads the destination file to verify the copy operation.
```java
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
// 1. Create a source file and write some content to it
BufferedWriter out1 = new BufferedWriter(new FileWriter("srcfile"));
out1.write("string to be copied\n");
out1.close();
// 2. Set up input and output streams for the copy operation
InputStream in = new FileInputStream(new File("srcfile"));
OutputStream out = new FileOutputStream(new File("destnfile"));
// 3. Copy the file contents using a 1024-byte buffer
byte[] buf = new byte;
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Close the streams to release system resources
in.close();
out.close();
// 4. Read and print the contents of the destination file to verify the copy
BufferedReader in1 = new BufferedReader(new FileReader("destnfile"));
String str;
while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in1.close();
}
}
```
### Output
```text
string to be copied
```
---
## 2. Modern and Efficient Alternatives
While the classic byte-buffer approach is educational, modern Java provides cleaner, more robust, and higher-performing APIs for copying files.
### Method A: Using Java NIO `Files.copy()` (Recommended)
Introduced in Java 7, the `java.nio.file.Files` class provides a one-line utility method to copy files. It is highly optimized and handles OS-level optimizations automatically.
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class NioCopyExample {
public static void main(String[] args) {
Path source = Paths.get("srcfile");
Path destination = Paths.get("destnfile");
try {
// REPLACE_EXISTING replaces the destination file if it already exists
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully using NIO!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
### Method B: Using Java NIO `FileChannel` (For Large Files)
For very large files, using `FileChannel`'s `transferTo()` or `transferFrom()` method can be significantly faster because it can leverage the operating system's zero-copy capability.
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class ChannelCopyExample {
public static void main(String[] args) {
try (FileChannel sourceChannel = new FileInputStream("srcfile").getChannel();
FileChannel destChannel = new FileOutputStream("destnfile").getChannel()) {
// Transfer bytes directly from the source channel to the destination channel
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
System.out.println("File copied successfully using FileChannel!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
---
## 3. Key Considerations
When implementing file copy operations in production environments, keep the following best practices in mind:
* **Resource Management (Try-with-Resources):** Always close your streams and channels to prevent memory leaks. In modern Java, use the `try-with-resources` statement to automatically close resources.
* **Buffer Size:** If you are using the traditional stream-based method, a buffer size of `4096` bytes (4KB) or `8192` bytes (8KB) is generally recommended for optimal performance on modern hardware.
* **Error Handling:** File operations are prone to runtime issues (e.g., file not found, permission denied, disk full). Always wrap your code in `try-catch` blocks and handle `IOException` appropriately.
* **Overwriting Files:** When using `Files.copy()`, specify `StandardCopyOption.REPLACE_EXISTING` if you want to overwrite the destination file; otherwise, the program will throw a `FileAlreadyExistsException`.
YouTip