Java 8 iterate, check and read files

Problem

Working with files is a trivial task when you have good API and could be a nightmare otherwise. Fortunatelly in java 8 is easy to iterate, rename, read etc files.

Solution listing files with NIO.2

If you need to list all files (in the example csv files) from a directory (non recursively then you can use method list:

try (Stream<Path> stream = Files.list(Paths.get("c:\\user\folder"))) {
    stream.map(String::valueOf)
        .filter(path -> path.endsWith(".csv"))
        .forEach(System.out::println);
}

result is:

file1.csv
file2.csv

It implements AutoCloseable, which means that code should be encapsulated with try-with-resources block in order to ensure that the stream's close method is invoked.

Solution "file walking" and find with NIO.2

When you need to recursively iterate over folder and it's subfolders then you can use **walk **:

try (Stream<Path> stream = Files.walk(Paths.get("c:\\user\\folder"), 3)) {
    stream.map(String::valueOf).
          filter(path -> path.endsWith(".csv")).
          forEach(System.out::println);
}

result is:

file1.csv
file2.csv
file3.csv - file in sub folder

A more efficient way may be to use find. Searching files starting at the given folder which is considered as root of the file tree. The number is maximum of directory levels to search given by the parameter maxDepth.

try (Stream<Path> stream = Files.find(Paths.get("c:\\user\\folder"), 2, 
                                        (path, attr) -> String.valueOf(path).endsWith(".csv"))) {
    stream.map(String::valueOf).forEach(System.out::println);
}

Solution read files

Reading files with java 8 is very easy:

Path path = Paths.get("c:\\user\\folder\\somefile.txt");
try {
    List<String> lines = Files.readAllLines(path);
} catch (IOException e) {
    // something failed
    e.printStackTrace();
}

Solution verify file existence

If you need to verify a file before opening it or creating new one you can use:

Path path = Paths.get("c:\\user\\folder\\somefile.txt");
boolean exists = Files.exists(path, new LinkOption[]{ LinkOption.NOFOLLOW_LINKS});

If you want to copy, delete or move file with java 8 :

java 8 copy move and delete files/

Related Article