Donate : Link
Medium Blog : Link
Applications : Link
You’ll learn how to copy a file or directory in Java using various methods like Files.copy() or using BufferedInputStream and BufferedOutputStream.
Java Copy File using Files.copy()
Java NIO’s Files.copy() method is the simplest way of copying a file in Java.
package com.example.java.programming.file;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class CopyFileExample {
public static void main(String... args) {
Path sourceFilePath = Paths.get("folder/folder1/test.txt");
Path targetFilePath = Paths.get("folder/folder2/test.txt");
try {
Files.copy(sourceFilePath, targetFilePath);
System.out.println("Done");
} catch (FileAlreadyExistsException ex) {
System.out.println("File already exists");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Output :
Done
The Files.copy() method will throw FileAlreadyExistsException if the target file already exists. If you want to replace the target file then you can use the REPLACE_EXISTING option like this –
Files.copy(sourceFilePath, targetFilePath, StandardCopyOption.REPLACE_EXISTING);
Java Copy File using BufferedInputStream and BufferedOutputStream
You can also copy a file byte-by-byte using a byte-stream I/O. The following example uses BufferedInputStream to read a file into a byte array and then write the byte array using BufferedOutputStream.
You can also use a FileInputStream and a FileOutputStream directly for performing the reading and writing. But a Buffered I/O is more performant because it buffers data and reads/writes it in chunks.
package com.example.java.programming.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author code.factory
*
*/
public class CopyFileExample {
public static void main(String... args) {
Path sourceFilePath = Paths.get("folder/folder1/test.txt");
Path targetFilePath = Paths.get("folder/folder2/test.txt");
try (InputStream inputStream = Files.newInputStream(sourceFilePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
OutputStream outputStream = Files.newOutputStream(targetFilePath);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
byte[] buffer = new byte[4096];
int numBytes;
while ((numBytes = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, numBytes);
}
System.out.println("Done");
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
}
}
Output :
Done

