4

to get subdirectories of a directory I am currently using

Paths.get(currentpath.toString(), "subdirectory");

is there a better method? I specifically do not like the toString call, and I'd prefer to not use .toFile() if possible.

I tried searching for this here but I only found answers about the old api or what I was currently using or completely unrelated questions.

3
  • 1
    Do you want all subdirs or just a specific one? Commented Feb 11, 2020 at 14:08
  • 1
    Perhaps Path.resolve​(Path other)? Commented Feb 11, 2020 at 14:15
  • @deHaar I want a specific one. Commented Feb 11, 2020 at 14:31

1 Answer 1

3

You can just resolve the name of the subdirectory against the root Path like this:

public static void main(String[] args) {
    // definition of the root directory (adjust according to your system)
    String currentPath = "C:\\";
    Path root = Paths.get(currentPath);

    // get a specific subdirectory by its name
    String specificSubDir = "temp";
    // resolve its name against the root directory
    Path specificSubDirPath = root.resolve(specificSubDir);

    // and check the result
    if (Files.isDirectory(specificSubDirPath)) {
        System.out.println("Path " + specificSubDirPath.toAbsolutePath().toString()
                + " is a directory");
    } else {
        System.err.println("Path " + specificSubDirPath.toAbsolutePath().toString()
                + " is not a directory");
    }
}

Since I have a directory C:\temp\, the output on my system is

Path C:\temp is a directory
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, this is exactly what I wanted, I was unfamiliar with the keyword resolve in this case. I also was only looking through Paths and Files

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.