Copying a Directory in Java
Learn to copy a directory into a new location in Java. We will see examples for copying only the directories, as well as, deep copying the directory (all sub-folders and all files).
1. Using Apache Commons IO’s FileUtils
FileUtils class provides a clean way for copying files and directories. It provides copyDirectory() method.
- copyDirectory() copies the contents of the specified source directory to the specified destination directory.
- The destination directory is created if it does not exist.
- If the destination directory did exist, then this method merges the source with the destination.
The copyDirectory() is an overloaded method with the following parameters:
- srcDir : an existing directory to copy, must not be null.
- destDir : the new directory, must not be null.
- filter : the filter to apply, null means copying all directories and files.
- preserveFileDate : true if the last modified date of the copy should be the same as the original.
copyDirectory(File srcDir, File destDir, boolean preserveFileDate) copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)
1.2 FileFilter and IOFileFilter
The second version of the method helps in copying only a filtered list of files. For example, if we want to copy only log files from one directory to another directory, we can use the FileFilter class.
We can also use the following builtin filters as per requirement:
- DirectoryFileFilter.DIRECTORY – it accepts files that are directories.
- FileFileFilter.FILE – it accepts files that are files (not directories).
Additionally, we can define our own custom filters as explained in this article.
The IOFileFilter helps in building the complex filters by chaining them with and() and or() methods. For example, the given complexFilter will help in copying all files that are either directories or text files.
IOFileFilter txtFileFilter = FileFilterUtils.suffixFileFilter(".txt"); IOFileFilter complexFilter = DirectoryFileFilter.DIRECTORY.or(txtFileFilter);
1.3. Java Program to Copy Only the Directory Structure
Given Java program copies all the directories (and subdirectories) from the source location to the destination location. No file is copied at any level.
File srcDir = new File("c:\\temp"); File destDir = new File("c:\\tempNew"); FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);
1.4. Java Program to Copy Subdirectories and only Text Files
Given Java program copies all the directories (and inner directories) from the source location to the destination location. It also searches and copies all the text files in any of the directories.
IOFileFilter txtFileFilter = FileFilterUtils.suffixFileFilter(".txt"); IOFileFilter complexFilter = DirectoryFileFilter.DIRECTORY.or(txtFileFilter); FileUtils.copyDirectory(srcDir, destDir, complexFilter, true);
1.5. Java Program to Copy All Subdirectories and Files
Do not include any filter if we want to deep copy all subdirectories and files.
FileUtils.copyDirectory(srcDir, destDir, true);
2. Copying Files Recursively using NIO
To deep copy a directory from one location to another with all its sub-folders and multiple files in them, Java does not provide a straightforward API.
We need to use java.nio.file.Files class. Its methods walkFileTree() and copy() must be used together to build a solution for deep copying a directory in Java using native APIs.
Java program for copying all the subdirectories and files c:\temp to a new location c:\tempNew .
File srcDir = new File("c:\\temp"); File destDir = new File("c:\\tempNew"); copyFolder(srcDir.toPath(), destDir.toPath()); //Copy methods public static void copyFolder(Path src, Path dest) throws IOException < try (Streamstream = Files.walk(src)) < stream.forEach(source ->copy(source, dest.resolve(src.relativize(source)))); > > private static void copy(Path source, Path dest) < try < Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING); >catch (Exception e) < throw new RuntimeException(e.getMessage(), e); >>
In the above Java program:
- If the target directory exists, the system will throw FileAlreadyExistsException .
- StandardCopyOption.REPLACE_EXISTING will replace the file with the new file if a file already exists in the destination folder. If we do not use this option, the copy will fail if the target file exists.
Verify that files are correctly copied or not. Feel free to modify the code and use it the way you like.
Copy a Directory in Java
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Introduction
In this short tutorial, we’ll see how to copy a directory in Java, including all its files and subdirectories. This can be achieved by using core Java features or third-party libraries.
2. Using the java.nio API
Java NIO has been available since Java 1.4. Java 7 introduced NIO 2 that brought a lot of useful features like better support for handling symbolic links, file attributes access. It also provided us with classes such as Path, Paths, and Files that made file system manipulation much easier.
Let’s demonstrate this approach:
public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException < Files.walk(Paths.get(sourceDirectoryLocation)) .forEach(source -> < Path destination = Paths.get(destinationDirectoryLocation, source.toString() .substring(sourceDirectoryLocation.length())); try < Files.copy(source, destination); >catch (IOException e) < e.printStackTrace(); >>); >
In this example, we walked the file tree rooted at the given source directory using Files.walk() and invoked Files.copy() for each file or directory we found in the source directory.
3. Using the java.io API
Java 7 was a turning point from the file system management perspective since it introduced a lot of new handy features.
However, if we want to stay compatible with older Java versions, we can copy a directory using recursion and java.io.File features:
private static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException < if (!destinationDirectory.exists()) < destinationDirectory.mkdir(); >for (String f : sourceDirectory.list()) < copyDirectoryCompatibityMode(new File(sourceDirectory, f), new File(destinationDirectory, f)); >>
In this case, we’ll create a directory in the destination directory for every directory in the source directory tree. Then we’ll invoke the copyDirectoryCompatibityMode() method:
public static void copyDirectoryCompatibityMode(File source, File destination) throws IOException < if (source.isDirectory()) < copyDirectory(source, destination); >else < copyFile(source, destination); >>
Also, let’s see how to copy a file using FileInputStream and FileOutputStream:
private static void copyFile(File sourceFile, File destinationFile) throws IOException < try (InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(destinationFile)) < byte[] buf = new byte[1024]; int length; while ((length = in.read(buf)) >0) < out.write(buf, 0, length); >> >
4. Using Apache Commons IO
Apache Commons IO has a lot of useful features like utility classes, file filters, and file comparators. Here we’ll be using FileUtils that provide methods for easy file and directory manipulation, i.e., reading, moving, copying.
Let’s add commons-io to our pom.xml file:
Finally, let’s copy a directory using this approach:
public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException
As shown in the previous example, Apache Commons IO makes it all much easier, since we only need to call FileUtils.copyDirectory() method.
5. Conclusion
This article illustrated how to copy a directory in Java. Complete code samples are available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: