Reputation: 312
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.
Upvotes: 4
Views: 1229
Reputation: 18558
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
Upvotes: 3