首页 > 解决方案 > 从路径中检索最后一级目录名称

问题描述

我有一个代表路径的字符串......像这样:

/A/B/C/D/E/{id}/{file_name}.ext

路径结构可能不同,但通常我想在文件名之前检索最后一个目录名(在示例 {id} 中)。

我想使用 Path java 类。

有没有一种简单安全的方法来使用 Path 类检索最后一个目录名称?

标签: javaparsingpath

解决方案


您可以使用getName()with Filewhich is available

参考:https ://docs.oracle.com/javase/6/docs/api/java/io/File.html#getName%28%29

File f = new File("C:\\Dummy\\Folder\\MyFile.PDF");
System.out.println(f.getName());

哪个回报你MyFile.PDF

(或者)

// Path object
Path path
    = Paths.get("D:\\eclipse\\configuration"
                + "\\myconfiguration.conf");

// call getName(int i) to get
// the element at index i
Path indexpath = path.getName(path.getNameCount()-2);

// prints the name
System.out.println("Name of the file : " + indexpath);

哪个打印myconfiguration.conf。希望能帮助到你 !


推荐阅读