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

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

问题描述

如何从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");

推荐答案

使用 FilegetParentFile() 方法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屋!

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