How do I delete multiple files in a directory in Java?

You can delete files, directories or links. With symbolic links, the link is deleted and not the target of the link. With directories, the directory must be empty, or the deletion fails.

The Files class provides two deletion methods.

The method deletes the file or throws an exception if the deletion fails. For example, if the file does not exist a NoSuchFileException is thrown. You can catch the exception to determine why the delete failed as follows:

try {
    Files.delete(path);
} catch (NoSuchFileException x) {
    System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
    System.err.format("%s not empty%n", path);
} catch (IOException x) {
    // File permission problems are caught here.
    System.err.println(x);
}

The method also deletes the file, but if the file does not exist, no exception is thrown. Failing silently is useful when you have multiple threads deleting files and you don't want to throw an exception just because one thread did so first.

Previous articles in this series have covered reading files with Java, writing files, and constructing directory and file paths with the

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
9 and

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
0 classes. This fourth part describes the most important directory and file operations. It answers the following questions:

  • How to list all files in a directory?
  • How to search for files matching specific criteria within a directory tree?
  • How to find the current directory?
  • How to find the user's home directory?
  • How to find the temporary directory, and how to create a temporary file?
  • How do I move files with Java?
  • How do I rename a file?
  • How do I copy a file?
  • How to delete a file?
  • How to create a symbolic link with Java?

The article answers all questions using the NIO.2 File API, introduced in Java 7 with JSR 203.

Directory operations

For the following directory operations, you need a Path-object representing the directory. You can construct this object using the static method

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
1 (or, before Java 11, using

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
2).

A comprehensive tutorial on constructing directory paths with

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
0,

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
4, and

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
9 can be found in the third part of this series.

How to list directory contents with Files.list()

The easiest way to list the complete contents of a directory is the

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
6 method. It returns a Stream of

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
0 objects, which we simply write to

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
8 in the following example:

Path currentDir = Path.of(System.getProperty("user.home")); Files.list(currentDir).forEach(System.out::println);

Code language: Java (java)

How to search a directory recursively with Files.list()

Let's move on to a more complex case. In the following example, we want to output all regular files located in the home directory or a subdirectory of any depth thereof and whose name starts with "settings".

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)

You can use the methods

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
9 and

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
0 to check if a file is a regular file or directory. Another file type is the symbolic link – you can recognize it with

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
1. It is also possible that all three methods return

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
2, in which case the file is of type "other" (what exactly this could be is unspecified).

In the example above, we have to catch

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
3 inside the lambda and wrap it with an

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
4 because the

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
5 consumer of the stream must not throw a checked exception.

How to search a directory recursively with Files.walk()

You can write the previous example much shorter and more elegant – using

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
6:

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)

However, this variant has the disadvantage that an

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
7 cannot be caught individually as before. If such an exception occurs here, the entire

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
6 method terminates. If this is acceptable for your application, this way is more beautiful than the previous one.

How to search a directory recursively with Files.walkFileTree()

Another variant is

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
9. This method implements the visitor pattern. It sends each file within the directory structure to a

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

Code language: Java (java)
0, which you pass to the method. In the following example, we use the

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

Code language: Java (java)
1 class, which implements all methods of

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

Code language: Java (java)
0. We only override the

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

Code language: Java (java)
3 method:

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)

The method's return value,

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

Code language: Java (java)
4, indicates that

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

Code language: Java (java)
5 should continue to traverse the directory tree. Other return values would be:

  • private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

    Code language: Java (java)
    6 – terminates the

    private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

    Code language: Java (java)
    5 method.
  • private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

    Code language: Java (java)
    8 – skips all other files of the current directory.
  • private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

    Code language: Java (java)
    9 – skips the current directory – this return value cannot be returned by

    private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

    Code language: Java (java)
    3, but by

    private static void findFileWithFind(Path currentDir, String fileNamePrefix) throws IOException { Files.find(currentDir, Integer.MAX_VALUE, (path, attributes) -> Files.isRegularFile(path) && path.getFileName().toString().startsWith(fileNamePrefix)) .forEach(System.out::println); }

    Code language: Java (java)
    1.

The

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

Code language: Java (java)
5 variant, too, would terminate processing in the case of an

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
7. However, there is a way to prevent this. To do so, you also need to overwrite the method

private static void findFileWithFind(Path currentDir, String fileNamePrefix) throws IOException { Files.find(currentDir, Integer.MAX_VALUE, (path, attributes) -> Files.isRegularFile(path) && path.getFileName().toString().startsWith(fileNamePrefix)) .forEach(System.out::println); }

Code language: Java (java)
4:

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { if (exc instanceof AccessDeniedException) { System.out.println("Access denied: " + file); return FileVisitResult.CONTINUE; } else { return super.visitFileFailed(file, exc); } } }); }

Code language: Java (java)

How to search a directory with Files.find()

An alternative approach is the

private static void findFileWithFind(Path currentDir, String fileNamePrefix) throws IOException { Files.find(currentDir, Integer.MAX_VALUE, (path, attributes) -> Files.isRegularFile(path) && path.getFileName().toString().startsWith(fileNamePrefix)) .forEach(System.out::println); }

Code language: Java (java)
5 method. It expects a "matcher" as the third parameter: this is a function that has a

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
0 and

private static void findFileWithFind(Path currentDir, String fileNamePrefix) throws IOException { Files.find(currentDir, Integer.MAX_VALUE, (path, attributes) -> Files.isRegularFile(path) && path.getFileName().toString().startsWith(fileNamePrefix)) .forEach(System.out::println); }

Code language: Java (java)
7 as input parameters and returns a

private static void findFileWithFind(Path currentDir, String fileNamePrefix) throws IOException { Files.find(currentDir, Integer.MAX_VALUE, (path, attributes) -> Files.isRegularFile(path) && path.getFileName().toString().startsWith(fileNamePrefix)) .forEach(System.out::println); }

Code language: Java (java)
8 indicating whether the corresponding file should be included in the result or not.

private static void findFileWithFind(Path currentDir, String fileNamePrefix) throws IOException { Files.find(currentDir, Integer.MAX_VALUE, (path, attributes) -> Files.isRegularFile(path) && path.getFileName().toString().startsWith(fileNamePrefix)) .forEach(System.out::println); }

Code language: Java (java)

Again, an

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
7 would end the entire search prematurely. I don't know of any way to circumvent this with

private static void findFileWithFind(Path currentDir, String fileNamePrefix) throws IOException { Files.find(currentDir, Integer.MAX_VALUE, (path, attributes) -> Files.isRegularFile(path) && path.getFileName().toString().startsWith(fileNamePrefix)) .forEach(System.out::println); }

Code language: Java (java)
5. If you expect subdirectories with denied access, you should either use

private static void findFileWithWalkFileTree( Path currentDir, String fileNamePrefix) throws IOException { Files.walkFileTree(currentDir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(file) && file.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(file); } return FileVisitResult.CONTINUE; } }); }

Code language: Java (java)
9 and overwrite the

Path currentDir = Path.of(System.getProperty("user.dir"));

Code language: Java (java)
2 method to catch the exception. Alternatively, use

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
6 and implement the recursion yourself.

Accessing specific directories

Attention: If you are using a version older than Java 11, you must replace

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
1 with

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
2 in the following code examples.

Accessing the current directory

The current directory can be found via the system property "user.dir":

Path currentDir = Path.of(System.getProperty("user.dir"));

Code language: Java (java)

Accessing the user's home directory

You can find the home directory of the current user via the system property "user.home":

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)

Accessing the temporary directory

And you can find the temporary directory via the system property "java.io.tmpdir":

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)

If you want to create a temporary file in the temporary directory, you do not need to access the temporary directory first. There is a shortcut for this. You will find it at the beginning of the following chapter, "File operations".

File operations

How to create a temporary file

After the last chapter concluded with accessing the temporary directory, this one starts with a shortcut to creating temporary files:

Path tempFile = Files.createTempFile("happycoders-", ".tmp");

Code language: Java (java)

The two parameters are a prefix and a suffix. The

Path currentDir = Path.of(System.getProperty("user.dir"));

Code language: Java (java)
6 method will insert a random number between them. When I run the method repeatedly on my Windows system and print the variable

Path currentDir = Path.of(System.getProperty("user.dir"));

Code language: Java (java)
7 to the console, I get the following output:

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
0

On Linux it looks like this:

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
1

It is essential to know that

Path currentDir = Path.of(System.getProperty("user.dir"));

Code language: Java (java)
6 does not only create the respective

private static void findFileWithWalk(Path currentDir, String fileNamePrefix) throws IOException { Files.walk(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } }); }

Code language: Java (java)
0 object but actually creates an empty file.

How to move a file in Java

To move a file, use the method

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
0. The following example creates a temporary file and moves it to the home directory of the logged-on user:

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
2

The second parameter of the

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
1 method must represent the target file, not the target directory! If you invoked

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
2 here, you would get a

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
3. Therefore, in the example, we use the

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
4 method to concatenate the

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
5 with the name of the file to be copied.

How to move a directory including all subdirectories

You can move a directory just like a file. In the following example, we create two temporary directories and one file in the first directory. We then move the first directory into the second:

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
3

How to rename file with Java

After all, renaming a file (or a directory) is a special case of moving, with the destination directory being the same as the source directory and only the file name changing. In the following example, we rename a temporary file to "happycoders.tmp":

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
4

Invoking

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
6 is a shortcut for

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
7: The directory is extracted from the source file and concatenated with the new file name.

How to copy a file in Java

Copying a file is similar to renaming it. The following example copies a temporary file to the home directory:

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
5

This method has a significant advantage over proprietary implementations with

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
8 and

Path homeDir = Path.of(System.getProperty("user.home"));

Code language: Java (java)
9, as they were necessary before Java 7 and the NIO.2 File API:

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)
0 delegates the call to operating system-specific – and thus optimized – implementations.

How to delete a file in Java

You can delete a file (or a directory) with

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)
1:

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
6

The directory on which you invoke

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)
1 must be empty. Otherwise, the method will throw a

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)
3. You can try this with the following code:

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
7

First, a temporary directory is created, then a temporary file in it. Then an attempt is made to delete the (non-empty) directory.

You can create a symbolic link with the method

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)
4. Attention: You have to specify target and source in reverse order as with all previous methods: first, the link path, then the path of the file to be linked. The following example creates a temporary file and then sets a symbolic link to the created file from the home directory.

import java.io.*; import java.nio.file.*; public class FindFilesRecursivelyExample { public static void main(String[] args) throws IOException { Path currentDir = Path.of(System.getProperty("user.home")); findFileRecursively(currentDir, "settings"); } private static void findFileRecursively( Path currentDir, String fileNamePrefix) throws IOException { Files.list(currentDir).forEach(child -> { if (Files.isRegularFile(child) && child.getFileName().toString().startsWith(fileNamePrefix)) { System.out.println(child); } if (Files.isDirectory(child) ) { try { findFileRecursively(child, fileNamePrefix); } catch (AccessDeniedException e) { System.out.println("Access denied: " + child); } catch (IOException e) { throw new UncheckedIOException(e); } } }); } }

Code language: Java (java)
8

This example works on Linux without restrictions. On Windows, you need administrative rights to create symbolic links. If these are missing, the following exception is thrown:

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)
5

Summary and outlook

This fourth article in the series about files in Java introduced the most important directory and file operations.

In the next part, I will show you how to write and read structured data with

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)
6 and

Path tempDir = Path.of(System.getProperty("java.io.tmpdir"));

Code language: Java (java)
7.

We then move on to the following advanced topics:

  • NIO channels and buffers introduced in Java 1.4, to speed up working with large files
  • for convenient and blazing-fast file access without streams
  • , to access the same files in parallel – i.e., from several threads or processes – without conflict

As always, I appreciate it if you share the article or your feedback via the comment function. Would you like to be informed when the next part is published? Then to sign up for the HappyCoders newsletter.

How to delete multiple files from a folder in Java?

You can use the FileUtils. cleanDirectory() method to recursively delete all files and subdirectories within a directory, without deleting the directory itself. To delete a directory recursively and everything in it, you can use the FileUtils. deleteDirectory() method.

How to delete all the files in a directory in Java?

Method 1: using delete() to delete files and empty folders.
Provide the path of a directory..
Call user-defined method deleteDirectory() to delete all the files and subfolders..

How can we delete all files in a directory?

Another option is to use the rm command to delete all files in a directory..
Open the terminal application..
To delete everything in a directory run: rm /path/to/dir/*.
To remove all sub-directories and files: rm -r /path/to/dir/*.

How to delete the contents of a folder in Java?

How to delete a directory and its contents in Java.
Use the Files. walk method to walk through all the files of the directory. ... .
All the files are traversed in depth-first order. Reverse the stream and delete it from inner files..
Call Files. delete(path) to delete the file or directory..