Explain Codes LogoExplain Codes Logo

Copying files from one directory to another in Java

java
file-handling
io-operations
performance-optimization
Alex KataevbyAlex Kataev·Nov 8, 2024
TLDR

Easily copy a file in Java with Files.copy():

Files.copy( Paths.get("source/file.txt"), Paths.get("dest/file.txt"), StandardCopyOption.REPLACE_EXISTING // Because sometimes, the old must make way for the new );

This line moves file.txt from source to dest, overwriting if needed using java.nio.file APIs for efficient file I/O.

The 'big gulp' solution for directory copying is Apache Commons IO FileUtils.copyDirectory():

FileUtils.copyDirectory(new File("source_directory"), new File("dest_directory"));

Ensure Apache Commons IO is in your project's dependencies:

<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency>

Handling large and grouped files

FileChannel for performance

For 'larger than life' files, FileChannel.transferTo() turbocharges the process:

FileChannel sourceChannel = new FileInputStream("source/largefile.dat").getChannel(); // Grabbing the big one FileChannel destChannel = new FileOutputStream("dest/largefile.dat").getChannel(); // The big gulp location sourceChannel.transferTo(0, sourceChannel.size(), destChannel); // Gulp!

Ensure channels are closed in a finally block or use try-with-resources to auto-close.

NIO.2 for robust I/O operations

NIO.2's Files.walk() is your Sherpa through directory jungles, letting you filter and select files before moving:

Files.walk(Paths.get("source_directory")).forEach(sourcePath -> { Path destination = Paths.get("dest_directory", sourcePath.toString().substring("source_directory".length())); Files.copy(sourcePath, destination, StandardCopyOption.REPLACE_EXISTING); });

Error handling

Wrap file operations in a try-catch to handle possible I/O errors:

try { Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); // It's not you, it's me ― the file }

Third-party tools vs. Vanilla Java

Consider costs and benefits of third-party tools versus Java's built-in magic. Libraries like Apache Commons IO provide handiness but consider your project's requirements.

Nailing down the file path and type

Correct file paths

Avoid 'file not found' surprises ― properly format and resolve paths:

Path sourcePath = Paths.get("source_directory").resolve("file.txt"); // Specify source Path targetPath = Paths.get("dest_directory").resolve(sourcePath.getFileName()); // Visor down, target locked

Copying specific file types

Need to copy only text files? Dial in with FilenameFilter:

File[] textFiles = new File("source_directory").listFiles((dir, name) -> name.toLowerCase().endsWith(".txt")); // Fetch all .txt files for (File file : textFiles) { Files.copy( file.toPath(), Paths.get("dest_directory", file.getName()), StandardCopyOption.REPLACE_EXISTING ); } // Beep boop bop, all text files copied to the destination

Automatic subdirectory creation

Java can magically conjure subdirectories during copying:

Files.createDirectories(targetPath.getParent()); // I create, therefore I am Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); // Let the copy magic begin

Byte-fu for gurus

Buffers for optimized copying

To dial-in control, manually manage buffering:

try (InputStream in = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile))) { byte[] buffer = new byte[1024]; // One byte at a time, just like eating an elephant int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } } // Bytes in, bytes out. Just like a byte nightclub

Groovy for file operations

Remember Groovy? Its syntactic sugar can sweeten file operations while making it more readable.