简体   繁体   中英

Java - How to read all files in the same directory

I need to read all files in the same directory and store those files in a list. All files end in .txt and there are no subdirectory.

List<String> recipe = new ArrayList<>();
try {
    recipe = Files.readAllLines(Paths.get("gyro.txt"));
}

You can get an array of files (according to the specified folder), after that you can iterate by each file in the folder and add all the characters from the file. Can you please try to use the following code:

public static List<String> readFromAllFilesInDirectory(final String folderName) {
    File folder = new File(folderName);
    List<String> recipe = new ArrayList<>();
    for (final File file : Objects.requireNonNull(folder.listFiles())) {
        if (!file.isDirectory()) {
            try {
                recipe.addAll(Files.readAllLines(Paths.get(file.getPath())));
            } catch (Exception e) {
            }
        }
    }
    return recipe;
}

public static void main(String[] args) {
    File folder = new File("G:\\B\\1.txt");
    System.out.println(readFromAllFilesInDirectory(folder.getParent()));
}

Try use the FileNameFilter class: Java FileNameFilter interface has method boolean accept(File dir, String name) that should be implemented and every file is tested for this method to be included in the file list.

File directory = new File("D://");

File[] files = directory.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});
for (File file : files) {
    System.out.println(file.getAbsolutePath());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM