Getting the directory name in java

Note also that if you create a file this way (supposing "d:/test/" is current working directory):

File file = new File("test.java");

You might be surprised, that both getParentFile() and getParent() return null. Use these to get parent directory no matter how the File was created:

File parentDir = file.getAbsoluteFile().getParentFile();
String parentDirName = file.getAbsoluteFile().getParent();

With Java 7 there is yet another way of doing this:

Path path = Paths.get("d:/test/test.java"); 
Path parent = path.getParent();
//getFileName() returns file name for 
//files and dir name for directories
String parentDirName = path.getFileName().toString();

I (slightly) prefer this way, because one is manipulating path rather than files, which imho better shows the intentions. You can read about the differences between File and Path in the Legacy File I/O Code tutorial


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.

Tags:

Java

File Io