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 do I list files in a given directory using Files.list() method?

In Java, you can use the Files.list() method to list all files in a given directory. Files.list(Path dir) is a method in the java.nio.file.Files class.

This method returns a Stream that is lazily populated with Path by walking the directory tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the name of the directory entry against dir.

The stream is “lazy” because not all the Paths are populated at once. This can be beneficial if you have a large number of files in your directory.

Here’s a code snippet that shows you how to do it:

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 ListFiles {
    public static void main(String[] args) {
        // Replace with your directory
        Path path = Paths.get("D:/Games");

        // Use try-with-resources to get auto-closeable stream
        try (Stream<Path> paths = Files.list(path)) {
            paths
                    .filter(Files::isRegularFile)  // filter out subdirectories
                    .forEach(System.out::println); // print file names
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This code lists all files in the specified directory ("D:/Games" in this case). It uses a stream of Path obtained from Files.list(), filters out the paths that are not regular files using Files.isRegularFile(), and finally prints each file name using System.out.println().

Remember to replace "D:/Games" with the actual directory you want to list files from. Also, the Files.list() method throws an IOException, so you must handle this exception in a try-catch block or declare it in the method signature.

How do I set up JAVA_HOME and Path variables in Windows?

Setting up a JAVA_HOME and Path variables is the second thing you’ll need to do after installing a JDK (Java Development Kit). Although this is not required by Java itself, it is commonly use by other application. For instance then Apache Tomcat web application server and other application server will need it. Or we might need it if we want to compile or running our Java classes from the command prompt. It helps us to organize the default JDK and the execution path.

So here are the steps that we’ll need to do to configure the JAVA_HOME and Path variable on a Windows operating system.

Step 1. Finding the location of our JDK installation directory. If we already know where we have installed the JDK continue to the Step 2.

  1. The JDK usually installed in the C:\Program Files\Java directory by default.
  2. Under this directory we can find one or more versions of installed JDK, for examples I have jdk-14 and jdk-17. Just choose the default one we’re going to use.

Step 2. Setting JAVA_HOME variable

After we know the location of your JDK installation, we can copy the directory location from the Windows Explorer address bar.

  1. Open Windows Explorer
  2. Right-Click the Computer and select the Properties menu.
  3. Click Advanced system settings and the System Properties windows will be shown.
  4. Select the Advance tab.
  5. Click the Environment Variables button.
  6. A new Environment Variables window will be shown.
  7. Under the System Variables, click the New button to create a new environment variable.
  8. Enter the variable name as JAVA_HOME, all letters are in uppercase.
  9. In the variable value enter the JDK installation path you’ve copy above.
  10. Click OK.

Step 3. Setting the Path variable

After we’ve set the JAVA_HOME variable, now we can update the Path variable.

  1. In the Environment Variables window, under the System Variables section find a variable named Path.
  2. If we don’t have the Path variable we need to add one using the New button.
  3. If we already have the Path variable we’ll need to update its value, click Edit button to update.
  4. Add %JAVA_HOME%\bin; to the beginning of the Path variable value.
  5. Press OK to when we are done.
  6. Press another OK to close the Environment Variables window.

Step 4. Check to see if the settings work

  1. Open your Windows Command Prompt.
  2. Type java -version in the command line.
  3. If everything was set correctly we’ll see the running version of your installed Java JDK.

As an example on my Windows Command Prompt I have something like:

D:\>java -version
java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)
Java HotSpot(TM) 64-Bit Server VM (build 17+35-LTS-2724, mixed mode, sharing)

If you don’t see the correct output, for instance you get an error like “‘java’ is not recognized as an internal or external command, operable program or batch file.”, please retry the steps described above. Enjoy your new adventure with Java programming. Happy coding!

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);
    }
}