How to get just the parent directory name of a spe

2019-01-04 01:44发布

How to get ddd from the path name where the test.java resides.

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");

8条回答
萌系小妹纸
2楼-- · 2019-01-04 02:06

Use File's getParentFile() method and String.lastIndexOf() to retrieve just the immediate parent directory.

Mark's comment is a better solution thanlastIndexOf():

file.getParentFile().getName();

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/ffffd

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-01-04 02:11

Use below,

File file = new File("file/path");
String parentPath = file.getAbsoluteFile().getParent();
查看更多
登录 后发表回答