开发者

Getting the directory name in java

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.


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.


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


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


File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜