Search code examples
javafiledirectoryfilereadersubdirectory

SubFolders not showing text files - JAVA


So I'm trying to make a student attendance by reading text files(all files are filled with names of students) from a folder[main folder is named Attendance], which folder has 2 sub-folders, and my program is not showing any text file, below is the code where I've created a File where, the path of the main folder is saved, and then created a List to store all files :

 File folder = new File("C:\\Users\\HP\\IdeaProjects\\AdaptiveJava\\src\\StudentAttendance\\Attendance");
 List<File> allFiles = Arrays.asList(folder.listFiles());

and so I have a method to print all text files that are inside the main folder :

  public static void printFileNames(List<File> fileList){
        for(int i = 0; i < fileList.size();i++){
            if(fileList.get(i).isFile()){
                System.out.println(fileList.get(i).getName());
            }
        }
    }

but is not printing anything, but when I change the file path e.g to

File folder = new File("C:\\Users\\HP\\IdeaProjects\\AdaptiveJava\\src\\StudentAttendance\\Attendance\\SubFolder1");

it prints all text files that are inside sub-folder and vice versa. What am I doing wrong here? How should multiple text-files be read from sub-folders?


Solution

  • You should also list the files in the subfolder, the method listFiles() only list the files relative to the folder you are in, so you can iterate over the first list of files and then list the files for each subfolder, this is an approach using java 8 streams:

    List<File> allFiles = Arrays.stream(folder.listFiles())
                    .filter(File::isDirectory)
                    .flatMap(f -> Arrays.stream(f.listFiles()))
                    .collect(Collectors.toList());
    

    You can also accomplish that using a for to iterate over the result of the first listFiles call, and call that method for every of the files asking first if it's a directory, something like this:

            List<File> allFiles = new ArrayList<>();
            for (File f : folder.listFiles()) {
                if (f.isDirectory()) {
                    allFiles.addAll(Arrays.asList(f.listFiles()));
                }
            }