如何获取特定文件的父目录名称 [英] How to get just the parent directory name of a specific file

查看:257
本文介绍了如何获取特定文件的父目录名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆