-2

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"));
}
kevin
  • 286
  • 3
  • 13
  • See https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path,java.lang.String) – Boris the Spider Nov 12 '20 at 20:29
  • see this post hope this will help https://stackoverflow.com/questions/29939379/reading-all-text-files-in-a-directory-in-java – Umair Mubeen Nov 12 '20 at 20:29
  • duplicate of https://stackoverflow.com/questions/1844688/how-to-read-all-files-in-a-folder-from-java – Tooster Nov 12 '20 at 20:30
  • 1
    @Umair why are you recommending an answer using an ancient and clunky API when newer and simpler things exist? – Boris the Spider Nov 12 '20 at 20:31
  • 1
    Does this answer your question? [How to read all files in a folder from Java?](https://stackoverflow.com/questions/1844688/how-to-read-all-files-in-a-folder-from-java) – tgdavies Nov 12 '20 at 20:43

2 Answers2

0

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()));
}
Andrian Soluk
  • 474
  • 6
  • 12
0

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());
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36