How do I use Files.walk() method to read directory contents?

The Files.walk() method in Java is a handy method when it comes to reading directory contents. Files.walk() method returns a Stream object that you can use to process each of the elements (files or directories) in the directory structure.

This method walks the file tree in a depth-first manner, starting from the given path that you provide as its parameter. It visits all files and directories in the file tree.

Here’s a simple example of how to use it. In this case, we are printing out the path to each file/directory.

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FileWalkExample {
    public static void main(String[] args) {
        Path start = Paths.get("D:/Games");
        try (Stream<Path> stream = Files.walk(start)) {
            stream.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Files.walk() also supports a maximum depth argument, so you can limit how deep into the directory structure you want to go. For example, Files.walk(start, 2) would only go two levels deep.

Please note: You should always close the stream after you’re done with it to free up system resources. This is done automatically here with a try-with-resources statement.

How to read file using Files.newBufferedReader?

In the snippet below you’ll learn to open file for reading using Files.newBufferedReader() method in JDK 7. This method returns a java.io.BufferedReader which makes a backward compatibility with the old I/O system in Java.

To read a file you’ll need to provide a Path and the Charset to the newBufferedReader() method arguments.

package org.kodejava.io;

import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FilesNewBufferedReader {
    public static void main(String[] args) {
        Path logFile = Paths.get("app.log");
        try (BufferedReader reader =
                     Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I move a file in JDK 7?

In the following code snippet you will learn how to move a file using the java.nio.file.Files helper class of JDK 7. This class simplify how you can move file. To move file you need to define the Path of the source and the target file.

We use the Files.move() method to move the file by passing the source and target path. We can also define the CopyOptions of the move process. For example to tell the move operation to replace the target file if the file already exist we can use the StandardCopyOption.REPLACE_EXISTING option. This option is a varargs, that means we can pass multiple options.

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.nio.file.StandardCopyOption.*;

public class FileMoveDemo {
    public static void main(String[] args) {
        // Define the source and target of the file to be moved.
        Path source = Paths.get("F:/Temp/data.txt");
        Path target = Paths.get("F:/Temp/data.bak");

        try {
            // Move file from source to target using the defined
            // configuration (REPLACE_EXISTING)
            Files.move(source, target, REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to recursively list all text files in a directory?

In this example you’ll learn how to use the Files.walkFileTree() to walk through file tree. This method requires two parameters. The first parameter is the starting file, in this example we’ll start from drive F:/Temp. And the second parameter is the file visitor to invoke for each file. Here we’ll create a file visitor call FindTextFilesVisitor which extend the java.nio.file.SimpleFileVisitor.

To get all the text files (files end with .txt) we override the visitFile() defined by the SimpleFileVisitor. In this method we check if the file ends with .txt extension and print the file name when the extension matches. And we continue to walk the file tree by returning FileVisitResult.CONTINUE.

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class WalkFileTree {
    public static void main(String[] args) {
        try {
            Path startDir = Paths.get("F:/Temp");
            Files.walkFileTree(startDir, new FindTextFilesVisitor());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * FindTextFilesVisitor.
     */
    static class FindTextFilesVisitor extends SimpleFileVisitor<Path> {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith(".txt")) {
                System.out.println(file.getFileName());
            }
            return FileVisitResult.CONTINUE;
        }
    }
}

Instead of listing files, you can modify the code snippet above for instance use it to delete all the files that ends with .bak. Simply change the extension and replace the print-out statement with a file delete statement in the visitFile() method.

How do I remove redundant elements from a Path?

To eliminate redundant elements from a Path we can use the Path.normalize() method. For example in the following code snippet. When try accessing the README file in the current directory the . symbol in the Path elements considered to be redundant, we don’t need it. That’s why we normalize the Path.

package org.kodejava.io;

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathNormalize {
    public static void main(String[] args) {
        // The following Path contains a redundant element. The "." which 
        // basically point to the current directory can simply be removed
        // when we are working on the current directory.
        Path path = Paths.get("./README.md");
        System.out.println("Path = " + path);

        // Removes redundant name elements from the path.
        path = path.normalize();
        System.out.println("Path = " + path);
    }
}