在java中获取目录名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3009981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the directory name in java
提问by Jony
How do I get the directory name for a particular java.io.File
on the drive in Java?
如何java.io.File
在 Java 中获取驱动器上特定目录的名称?
For example I have a file called test.java
under a directory on my D drive.
例如,我test.java
在 D 驱动器上的目录下有一个文件。
I want to return the directory name for this file.
我想返回这个文件的目录名。
采纳答案by skaffman
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.
请记住,java.io.File
代表目录和文件。
回答by Golmar
Note also that if you create a file this way (supposing "d:/test/" is current working directory):
另请注意,如果您以这种方式创建文件(假设“d:/test/”是当前工作目录):
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:
您可能会感到惊讶,getParentFile() 和 getParent() 都返回 null。无论文件是如何创建的,都可以使用这些来获取父目录:
File parentDir = file.getAbsoluteFile().getParentFile();
String parentDirName = file.getAbsoluteFile().getParent();
回答by Paperback Writer
With Java 7 there is yet another way of doing this:
在 Java 7 中,还有另一种方法可以做到这一点:
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 Codetutorial
我(稍微)更喜欢这种方式,因为一个人正在操纵路径而不是文件,恕我直言,这更好地表明了意图。您可以在Legacy File I/O Code教程中阅读 File 和 Path 之间的差异
回答by Storm
File file = new File("d:/test/test.java");
String dirName = file.getParentFile().getName();