Java — How to copy a File or Directory | Code Factory

Java Copy File using Files.copy()

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);
}
}
}
Done
Files.copy(sourceFilePath, targetFilePath, StandardCopyOption.REPLACE_EXISTING);

Java Copy File using BufferedInputStream and BufferedOutputStream

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);
}
}
}
Done

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store