如何仅获取特定文件的父目录名称 [英] 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
的 getParentFile()
方法 和 String.lastIndexOf()
到检索只是直接父目录.
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();
这些解决方案仅适用于文件具有父文件(例如,通过采用父 File
的文件构造函数之一创建的文件).当 getParentFile()
为 null 时,您需要使用 lastIndexOf
,或使用类似 Apache Commons 的 FileNameUtils.getFullPath()
一个>:
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屋!