[英]Getting the directory name in java
How do I get the directory name for a particular java.io.File
on the drive in Java?如何在 Java 驱动器上获取特定java.io.File
的目录名称?
For example I have a file called test.java
under a directory on my D drive.例如,我的 D 盘目录下有一个名为test.java
的文件。
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.请记住, java.io.File
表示目录和文件。
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 theLegacy File I/O Code tutorial您可以在Legacy File I/O Code教程中阅读 File 和 Path 之间的差异
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.您可能会感到惊讶,getParentFile() 和 getParent() 都返回 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.假设您在C:\\\\myfolder
目录中有一个名为test.java
的文件。 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
此代码将输出为C:\\\\myfolder
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.