Showing posts with label directory. Show all posts
Showing posts with label 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:

Saturday, January 8, 2022

How to read only specific file from folder and sub folder using Java

In this tutorial, we are going to learn how we can learn only specific files like .png or .jpg or any other file extension which are allocated inside folder and sub-folders.

Here, what we gonna do is to list all the folders and subfolders. After that looping through the folders to filter out and get the specific desired file from those folders.

Create a sample Java class called FolderFileReader.java

Create a method that lists all the subfolders present in the folder.

 public static void listDirSubDir(String directoryName, List<String> directoryList) throws Exception {
        File directory = new File(directoryName);
        File[] fList = directory.listFiles();
        if (fList != null)
            for (File file : fList) {
                if (file.isDirectory()) {
                    String folder = file.getAbsolutePath();
                    directoryList.add(folder);
                    listDirSubDir(folder, directoryList);
                }
            }
    }

We are using recursion in order to list all the subfolders and add the available folders to the List called directoryList

Now, let's create a method that will list all the files present in the particular folder.

public static ArrayList<String> getFolderFiles(String folder) throws Exception {
        ArrayList<String> FileList = new ArrayList<String>();
        FileExtensionFilter filter = new FileExtensionFilter(extension);
        File dir = new File(folder);
        if (!dir.isDirectory()) {
            throw new Exception("Directory does not exists: " + folder);
        }
        String[] list = dir.list(filter);
        assert list != null;
        if (list.length == 0) {
            System.out.println("File not found in this folder : " + dir.getName());
        }
        for (String file : list) {
            String temp = folder + File.separator + file;
            FileList.add(temp);
        }
        return FileList;
    }

The FileExtensionFilter is the filter class used to read specific file like .png or .jpg. 

Let's create the filter class

public static class FileExtensionFilter implements FilenameFilter {

        private String ext;

        public FileExtensionFilter(String ext) {
            this.ext = ext;
        }

        public boolean accept(File dir, String name) {
            return name.endsWith(this.ext);
        }
    }

Now, implement the main method

public static void main(String[] args) {
        String directory = "folder_path";
        ArrayList<String> directoryList = new ArrayList<>();
        try {
            directoryList.add(directory); // adding current directory
            listDirSubDir(directory, directoryList);
            System.out.println("Total directory found: " + directoryList.size());
            int totalFileFound = 0;
            for (String folder : directoryList) {
                ArrayList<String> files = getFolderFiles(folder);
                for (String file : files) {
                    System.out.println(file);
                }
                totalFileFound += files.size();
            }
            System.out.println("Total files found: " + totalFileFound);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Here, we are simply getting the list of folders available, looping through it, and getting the files present in each folder.

The overall implementation looks as below:

package io;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

public class FolderFileReader {

    private static final String extension = ".dcm";

    public static void main(String[] args) {
        String directory = "folder_path";
        ArrayList<String> directoryList = new ArrayList<>();
        try {
            directoryList.add(directory); // adding current directory
            listDirSubDir(directory, directoryList);
            System.out.println("Total directory found: " + directoryList.size());
            int totalFileFound = 0;
            for (String folder : directoryList) {
                ArrayList<String> files = getFolderFiles(folder);
                for (String file : files) {
                    System.out.println(file);
                }
                totalFileFound += files.size();
            }
            System.out.println("Total files found: " + totalFileFound);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void listDirSubDir(String directoryName, List<String> directoryList) throws Exception {
        File directory = new File(directoryName);
        File[] fList = directory.listFiles();
        if (fList != null)
            for (File file : fList) {
                if (file.isDirectory()) {
                    String folder = file.getAbsolutePath();
                    directoryList.add(folder);
                    listDirSubDir(folder, directoryList);
                }
            }
    }

    public static ArrayList<String> getFolderFiles(String folder) throws Exception {
        ArrayList<String> FileList = new ArrayList<String>();
        FileExtensionFilter filter = new FileExtensionFilter(extension);
        File dir = new File(folder);
        if (!dir.isDirectory()) {
            throw new Exception("Directory does not exists: " + folder);
        }
        String[] list = dir.list(filter);
        assert list != null;
        if (list.length == 0) {
            System.out.println("File not found in this folder : " + dir.getName());
        }
        for (String file : list) {
            String temp = folder + File.separator + file;
            FileList.add(temp);
        }
        return FileList;
    }

    public static class FileExtensionFilter implements FilenameFilter {

        private String ext;

        public FileExtensionFilter(String ext) {
            this.ext = ext;
        }

        public boolean accept(File dir, String name) {
            return name.endsWith(this.ext);
        }
    }
}
Share: