Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get specific subdirectory in java using paths

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.

like image 410
Slackow Avatar asked Sep 18 '25 08:09

Slackow


1 Answers

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
like image 115
deHaar Avatar answered Sep 19 '25 22:09

deHaar