Search code examples
javarecursiondirectorysubdirectory

How do you read in a file from a subdirectory in Java?


I have a Folder named Class and its two subdirectories are Lectures and Grades, and within those two subdirectories are txt files. How do I access the subdirectories (and maybe other subdirectories of the subdirectories Lectures and Grades)from the main directory - Class? I know I can use the absolute path in the code, but I would like to start from the starting folder, Class. So far, I have this as my code:

public class Test {
    public static void main(String[] args) {
        File directory = new File("/Users/Desktop/Class");
        File[] folder = directory.listFiles();
        for (File aFile : folder) {
            // Stuck here...
        }
    }
}

Sorry.. I'm new to Java..


Solution

  • You can recursively call the method to read the file in sub directories

    public static void main(String[] args) {
        File currentDir = new File("/Users/Desktop/Class"); // current directory
        displayDirectoryFiles(currentDir);
    }
    
    public static void displayDirectoryFiles(File dir) {
        try {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    System.out.println("directory:" + file.getCanonicalPath());
                    displayDirectoryContents(file);
                } else {
                    System.out.println("     file:" + file.getCanonicalPath());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    Handle the exception properly, currently just printing stacktrace