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"));
}
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());
}