如何获取特定文件的父目录名称 [英] How to get just the parent directory name of a specific file
问题描述
如何从test.java所在的路径名获取 ddd
。
How to get ddd
from the path name where the test.java resides.
File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
推荐答案
使用 File
's getParentFile()
方法和 String.lastIndexOf()
来检索 just 直接父目录。
Use File
's getParentFile()
method and String.lastIndexOf()
to retrieve just the immediate parent directory.
Mark的评论比 lastIndexOf()
更好:
Mark's comment is a better solution thanlastIndexOf()
:
file.getParentFile().getName();
这些解决方案仅适用于文件有父文件(例如,通过文件构造函数采取父母文件
)。当 getParentFile()
为空时,您需要使用 lastIndexOf
,或者使用 Apache Commons' FileNameUtils.getFullPath()
:
$ b
These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent File
). When getParentFile()
is null you'll need to resort to using lastIndexOf
, or use something like Apache Commons' FileNameUtils.getFullPath()
:
FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd
保留/尾随分隔符。您可以使用相同的 FilenameUtils
类从结果中获取名称,使用 lastIndexOf
等。
There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils
class to grab the name from the result, use lastIndexOf
, etc.
这篇关于如何获取特定文件的父目录名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!