Java Path File Name nio getFileNames(List fileNames, Path dir, String ext, boolean recursive)

Here you can find the source of getFileNames(List fileNames, Path dir, String ext, boolean recursive)

Description

Gets all files in target directory, with the given file extension.

License

Open Source License

Parameter

Parameter Description
ext The file extension to look for, e.g. '.g4'.
recursive If the folder should be recursively traversed.

Return

List of full file names.

Declaration

public static List<String> getFileNames(List<String> fileNames, Path dir, String ext, boolean recursive) 

Method Source Code

    //package com.java2s;
    //License from project: Open Source License 

    import java.io.IOException;

    import java.nio.file.DirectoryStream;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.util.ArrayList;
    import java.util.List;

    public class Main {
        /**//from  ww  w  .j av a 2s  .c om
         * Gets all files in target directory, with the given file extension. Returns an empty array list if nothing is
         * found or if an {@link IOException} occurs.
         *
         * @param ext The file extension to look for, e.g. '.g4'.
         * @param recursive If the folder should be recursively traversed.
         * @return List of full file names.
         */
        public static List<String> getFileNames(List<String> fileNames, Path dir, String ext, boolean recursive) {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        // Iterate over paths
        stream.forEach(p -> {
            if (p.toFile().isDirectory() && recursive) { // Directory
                getFileNames(fileNames, p, ext, true);
            } else { // File
                String fileName = p.toAbsolutePath().toString();

                if (fileName.endsWith(ext))
                    fileNames.add(fileName);
            }
        });
    } catch (IOException e) {
        return new ArrayList<>();
    }
    return fileNames;
}
    }

Related

  1. getFileName(String relativePath)
  2. getFileNameFromPath(String filePath)
  3. getFileNameFromPath(String str)
  4. getFilenameOrLastPath(String path)
  5. getFileNames(List fileNames, Path dir)
  6. getFileNames(List fileNames, Path dir, String sFilter)
  7. getFileNameWithoutExt(final Path file)
  8. getFilePath(String dirName)
  9. getFilePathName(Path filePath)