Java Reference
In-Depth Information
moving folders can fail in some cases, and deleting folders only works when the folder is empty. In
addition, you might be interested in writing a method that looks for a file or directory in a directory
as well as subdirectories.
For all these tasks, interfaces have been defined by the NIO2 API to do this. The reality, however, is
that implementing all interfaces and setting up everything can be a bit daunting for newcomers. For
instance, to walk over a directory tree, you'll need to implement FileVisitor<Path> with the pre-
VisitDirectory , visitFile , postVisitDirectory , and visitFileFailed methods. Look up the
Java API docs if you're interested to learn more.
Instead, the following Try It Out will present a set of alternative recursive methods you can use to
copy, move, delete, and search through directories, which you can use as a starting point in your
own code as well.
Using recursive Operations
try it out
In this Try It Out, you implement a set of methods to search, delete, copy, and move complete directo-
ries at once.
1.
In Eclipse, create a class called RecursiveOperations .
2.
First, add a method to delete files:
public static void delete(Path source) throws IOException {
if (Files.isDirectory(source)) {
for (Path file : getFiles(source))
delete(file);
}
Files.delete(source);
System.out.println("DELETED "+source.toString());
}
3.
Next, you need to provide the getFiles method. This helper method returns all files and subdi-
rectories in a given folder. However, since deletion will only work on empty folders, you want this
method to first return all directories, followed by all files to ensure that the delete method first
goes through all directories as far as possible:
public static List<Path> getFiles(Path dir) {
// Gets all files, but puts directories first
List<Path> files = new ArrayList<>();
if (!Files.isDirectory(dir))
return files;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry : stream)
if (Files.isDirectory(entry))
files.add(entry);
} catch (IOException | DirectoryIteratorException x) {
}
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry : stream)
if (!Files.isDirectory(entry))
Search WWH ::




Custom Search