How do I get the directory name for a particular java.io.File
on the drive in Java?
For example I have a file called test.java
under a directory on my D drive.
I want to return the directory name for this file.
In Java, we can use System. getProperty("user. dir") to get the current working directory, the directory from where your program was launched.
A Java Path instance represents a path in the file system. A path can point to either a file or a directory. A path can be absolute or relative. An absolute path contains the full path from the root of the file system down to the file or directory it points to.
Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.
getRoot() method of java. nio. file. Path used to return path object of the root component of this path object or null if this path does not have a root component.
File file = new File("d:/test/test.java");
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParent(); // to get the parent dir name
Remember, java.io.File
represents directories as well as files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With