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 get file basic attributes?

This example you’ll learn how to get file’s basic attributes. Basic file attributes are attributes that are common to many file systems and consist of mandatory and optional file attributes as defined by the BasicFileAttributes interface.

The file’s basic attributes include file’s date time information such as the creation time, last access time, last modified time. You can also check whether the file is a directory, a regular file, a symbolic link or something else. You can also get the size of the file.

Let’s see the code snippet below:

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

public class FileAttributesDemo {
    public static void main(String[] args) throws Exception {
        String path = "D:/resources/data.txt";

        Path file = Paths.get(path);
        BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("creationTime     = " + attr.creationTime());
        System.out.println("lastAccessTime   = " + attr.lastAccessTime());
        System.out.println("lastModifiedTime = " + attr.lastModifiedTime());

        System.out.println("isDirectory      = " + attr.isDirectory());
        System.out.println("isOther          = " + attr.isOther());
        System.out.println("isRegularFile    = " + attr.isRegularFile());
        System.out.println("isSymbolicLink   = " + attr.isSymbolicLink());
        System.out.println("size             = " + attr.size());
    }
}

The output of the code snippet:

creationTime     = 2021-05-05T17:09:09.0628061Z
lastAccessTime   = 2021-05-05T17:09:09.0628061Z
lastModifiedTime = 2021-11-04T00:11:43.279Z
isDirectory      = false
isOther          = false
isRegularFile    = true
isSymbolicLink   = false
size             = 0

How do I set file last modified time?

In the following code snippet you will learn how to update file’s last modified date/time. To update the last modified date/time you can use the java.nio.file.Files.setLastModifiedTime() method. This method takes two arguments. The first arguments is a Path object that represent a file, and the second arguments is the modified date in a FileTime object.

Let’s try the code snippet below.

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;

public class SettingFileTimeStamps {
    public static void main(String[] args) throws Exception {
        String path = "D:/resources/data.txt";
        Path file = Paths.get(path);

        BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("lastModifiedTime() = " + attr.lastModifiedTime());

        // Update the last modified time of the file.
        long currentTimeMillis = System.currentTimeMillis();
        FileTime fileTime = FileTime.fromMillis(currentTimeMillis);
        Files.setLastModifiedTime(file, fileTime);

        attr = Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("lastModifiedTime() = " + attr.lastModifiedTime());
    }
}

The output of the code snippet:

lastModifiedTime() = 2021-05-05T17:09:09.0628061Z
lastModifiedTime() = 2021-11-04T00:11:43.279Z