Showing posts with label read files inside directory. Show all posts
Showing posts with label read files inside directory. Show all posts

Friday, January 21, 2022

Read the files inside directory(folder) and subdirectory(sub folder) using Java 8+

In this tutorial, we are going to learn how we can read all the files and specific files inside the directory and subdirectory.

Let's create a sample class FileReader.java

Read all the directory subdirectory and files:

 public static void main(String[] args) {
        String directoryPath = "path_to_directory";
        try {
            List<String> allFiles = listFiles(directoryPath);
            for (String filePath : allFiles) {
                System.out.println(filePath);
            }
        } catch (IOException e) {
            System.out.println("Error due to: " + e.getMessage());
        }
    }
    public static List<String> listFiles(String directoryPath) throws IOException {
        Path start = Paths.get(directoryPath);
        try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
            return stream
                    .map(String::valueOf)
                    .sorted()
                    .collect(Collectors.toList());
        }
    }

listFiles() method list all the directory, subdirectory, and files present inside the given directory. We are using Files.walk which will return stream API; list the files, directory and subdirectory by walking through the start directory to the max level of the subdirectory. Integer.MAX_VALUE will go through the maximum level of subdirectories available.

Read all the files and folders inside the current directory:

    public static List<String> listFiles(String directoryPath) throws IOException {
        Path start = Paths.get(directoryPath);
        try (Stream<Path> stream = Files.walk(start, 1)) {
            return stream
                    .map(String::valueOf)
                    .sorted()
                    .collect(Collectors.toList());
        }
    }

Here, we are using 1 as a maximum level value instead of Integer.MAX_VALUE, so it will read the current directory.

Only read the files inside the directory and subdirectory:

    public static List<String> listFiles(String directoryPath) throws IOException {
        Path start = Paths.get(directoryPath);
        try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
            return stream
                    .map(String::valueOf)
                    .filter(file -> !new File(file).isDirectory())
                    .sorted()
                    .collect(Collectors.toList());
        }
    }

We are adding the filter that will only read files but not the directory or subdirectory and returns only files present inside the given directory.

Read Specific files inside directory and subdirectory

Suppose we want to only read .jpg or .png or .zip files present inside the directory and subdirectory. In this case, we will apply the filter to read only the desired extension file.

public static void main(String[] args) {
        String directoryPath = "path_to_directory";
        try {
            String fileExtensionToRead = ".png";
            List<String> pngFiles = listFiles(directoryPath, fileExtensionToRead);
            for (String filePath : pngFiles) {
                System.out.println(filePath);
            }
        } catch (IOException e) {
            System.out.println("Error due to: " + e.getMessage());
        }
    }
private static List<String> listFiles(String directoryPath, String ext) throws IOException {
        Path start = Paths.get(directoryPath);
        try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
            return stream
                    .map(String::valueOf)
                    .filter(file -> file.contains(ext))
                    .sorted()
                    .collect(Collectors.toList());
        }
    }

We are using a filter such that it will list the file if the filename contains the given extension. We can customize this filter as per our requirements.

The overall code implementation looks as below:

package io;

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

public class FileReader {

    public static void main(String[] args) {
        String directoryPath = "path_to_directory";
        try {
            List<String> allFiles = listFiles(directoryPath);
            for (String filePath : allFiles) {
                System.out.println(filePath);
            }
            String fileExtensionToRead = ".png";
            List<String> pngFiles = listFiles(directoryPath, fileExtensionToRead);
            for (String filePath : pngFiles) {
                System.out.println(filePath);
            }
        } catch (IOException e) {
            System.out.println("Error due to: " + e.getMessage());
        }
    }

    public static List<String> listFiles(String directoryPath) throws IOException {
        Path start = Paths.get(directoryPath);
        try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
            return stream
                    .map(String::valueOf)
                    .filter(file -> !new File(file).isDirectory())
                    .sorted()
                    .collect(Collectors.toList());
        }
    }

    private static List<String> listFiles(String directoryPath, String ext) throws IOException {
        Path start = Paths.get(directoryPath);
        try (Stream<Path> stream = Files.walk(start, Integer.MAX_VALUE)) {
            return stream
                    .map(String::valueOf)
                    .filter(file -> file.contains(ext))
                    .sorted()
                    .collect(Collectors.toList());
        }
    }
}
Share: