How to save a file with the specified extension under the directory specified in Java to the list

background

When it is necessary to operate a large number of files in Java, it is consistently easier to implement the listing part in Java than to list it with the find command of the terminal and then pass it to Java. So I wrote this code.

Code overview

This program takes the directory name and extension as arguments, searches the specified directory and the directories below it, and saves the file with the specified extension in ʻArrayList`. Here, find the m4a file in the iTunes folder and save it in the list.

The code above uses the new Java 8 lambda expressions (Lambda Expressions) and streams (Stream). See below for code that doesn't use lambda expressions and streams. (It may work with Java older than Java8.)

Java 8 or later

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.regex.Pattern;
import java.util.ArrayList;
import java.util.stream.Stream;

public class Utils {
    public static void main(String[] args) throws IOException {
        // To list up m4a files in iTunes directory
        Path rootDir = Paths.get(System.getProperty("user.home"), "Music", "iTunes");
        String extension  = "m4a";

        // for standard inputs
        if (args.length == 2) {
            rootDir = Paths.get(args[0]);
            extension   = args[1];
        } else if (args.length != 0){
            System.err.println("Error: set correct args.");
        }

        if (!Pattern.matches("^[0-9a-zA-Z]+$", extension)) {
            System.err.println("Error: set correct extension. (only alphabet and numeric)");
        } else {
            ArrayList<File> fileList = listUpFiles(rootDir, extension);
            for (File file : fileList) {
                System.out.println(file.getAbsolutePath());
            }
            System.out.println(fileList.size());    
        }
    }

    /**
     * list up files with specified file extension (extension)
     * under the specified directory (rootDir) recursively.
     * @param rootDir   : root directory
     * @param extension : string needs to be contained as file extension
     * @return          : list of files
     */
     public static ArrayList<File> listUpFiles(Path rootDir, String extension){
        String extensionPattern = "." + extension.toLowerCase();
        final ArrayList<File> fileList = new ArrayList();

        try (final Stream<Path> pathStream = Files.walk(rootDir)) {
            pathStream
                    .map(path -> Path::toFile)
                    .filter(file -> !file.isDirectory())
                    .filter(file -> file.getName().toLowerCase().endsWith(extensionPattern))
                    .forEach(fileList::add);
        } catch (final IOException e) {
            e.printStackTrace();
        }
        return (fileList);
    }
}

Code that doesn't use lambda expressions and streams

import java.io.File;
import java.util.regex.Pattern;
import java.util.ArrayList;

public class UtilsOld {

    public static void main(String[] args) {
        // To list up m4a files in iTunes directory
        String rootDirName = System.getProperty("user.home") + java.io.File.separator +
                             "Music" + java.io.File.separator + "iTunes";
        String extension  = "m4a";

        // for standard input
        if (args.length == 2) {
            rootDirName = args[0];
            extension   = args[1];
        } else if (args.length != 0){
            System.err.println("Error: set correct args.");
        }

        if (!Pattern.matches("^[0-9a-zA-Z]+$", extension)) {
            System.err.println("Error: set correct extension. (only alphabet and numeric)");
        } else {
            String extensionPattern = "." + extension.toLowerCase();

            ArrayList<File> fileList = new ArrayList();
            fileList = listUpFiles(rootDirName, extensionPattern, fileList);

            for (File file : fileList) {
                System.out.println(file.getAbsolutePath());
            }
            System.out.println(fileList.size());
        }
    }

    /**
     * list up files with specified file extension (ext)
     * under the specified directory (rootDirName) recursively.
     *
     * @param rootDirName      : root directory name
     * @param extensionPattern : regular expression pattern of file extension
     * @param fileArrayList    : ArrayList to store files
     * @return : return fileArrayList
     */
    public static ArrayList listUpFiles(String rootDirName, String extensionPattern, ArrayList<File> fileArrayList){
        File rootDir = new File(rootDirName);
        File[] listOfFiles = rootDir.listFiles();
        assert listOfFiles != null;

        for (File item : listOfFiles) {
            if (item.isDirectory()) {
                fileArrayList = listUpFiles(item.getAbsolutePath(), extensionPattern, fileArrayList);
            } else if (item.isFile()) {
                String fileName = item.getName().toLowerCase();
                if (fileName.endsWith(extensionPattern)) {
                    fileArrayList.add(item);
                }
            }
        }
        return(fileArrayList);
    }
}

reference

Comment from saka1029 https://www.javacodegeeks.com/2014/05/playing-with-java-8-lambdas-paths-and-files.html

Recommended Posts

How to save a file with the specified extension under the directory specified in Java to the list
How to get the absolute path of a directory running in Java
[Java] How to search for a value in an array (or list) with the contains method
[Java] Get the file path in the folder with List
How to convert a file to a byte array in Java
How to make a jar file with no dependencies in Maven
[chown] How to change the owner of a file or directory
How to get the length of an audio file in java
[Java] How to use the File class
[Java] How to get the current directory
How to get the date in java
[java tool] A tool that deletes files under the specified path by extension
[Personal memo] How to interact with a random number generator in Java
The story of forgetting to close a file in Java and failing
How to find out the Java version of a compiled class file
How to start a Docker container with a volume mounted in a batch file
Read a string in a PDF file with Java
How to get the ID of a user authenticated with Firebase in Swift
How to ZIP a JAVA CSV file and manage it in a Byte array
How to create a Java environment in just 3 seconds
[Java] How to omit the private constructor in Lombok
How to jump from Eclipse Java to a SQL file
java: How to write a generic type list [Note]
[Java] How to extract the file name from the path
How to create a data URI (base64) in Java
Organized how to interact with the JDK in stages
[How to insert a video in haml with Rails]
How to convert A to a and a to A using AND and OR in Java
How to debug the generated jar file in Eclipse
Use java1.7 (zulu7) under a specific directory with jenv
[Java] How to start a new line with StringBuilder
If you use SQLite with VSCode, use the extension (how to see the binary file of sqlite3)
Summary of how to use the proxy set in IE when connecting with Java
How to correctly check the local HTML file in the browser
How to take a screenshot with the Android Studio emulator
How to request a CSV file as JSON with jMeter
How to read your own YAML file (*****. Yml) in Java
How to connect the strings in the List separated by commas
How to create a placeholder part to use in the IN clause
I want to make a list with kotlin and java!
How to store a string from ArrayList to String in Java (Personal)
Uppercase only the specified range with substring. (How to use substring)
Create a method to return the tax rate in Java
How to select a specified date by code in FSCalendar
How to add the same Indexes in a nested array
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
Mapping to a class with a value object in How to MyBatis
How to develop and register a Sota app in Java
How to simulate uploading a post-object form to OSS in Java
How to derive the last day of the month in Java
About the behavior when doing a file map with java
How to switch Java in the OpenJDK era on Mac
How to set up a proxy with authentication in Feign
How to change the file name with Xcode (Refactor Rename)
Considering the adoption of Java language in the Reiwa era ~ How to choose a safe SDK
How to write comments in the schema definition file in GraphQL Java and reflect them in GraphQL and GraphQL Playground
How to reduce the load on the program even a little when combining characters with JAVA
How to create a jar file or war file using the jar command
[Rails / Routing] How to refer to the controller in the directory you created
How to cancel cell merging within a specified range with POI
How to make a Java container