23

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.

5 Answers 5

43
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.

Sign up to request clarification or add additional context in comments.

2 Comments

@skaffman Don't I get the parent directory name from file's pathname?
Did not work for me. getParent() returns null.
19

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

Comments

11

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();

1 Comment

This answer gets my green check.
0
File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();

Comments

0

Say that you have a file called test.java in C:\\myfolder directory. Using the below code, you can find the directory where that file sits.

String fileDirectory = new File("C:\\myfolder\\test.java").getAbsolutePath(); 
fileDirectory = fileDirectory.substring(0,fileDirectory.lastIndexOf("\\"));

This code will give the output as C:\\myfolder

Comments

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.