从路径中检索最后一级目录名称
Retrieve last level directory name from path
我有一个代表路径的字符串......像这样:
/A/B/C/D/E/{id}/{file_name}.ext
路径结构可能不同,但通常我想检索文件名之前的最后一个目录名(在示例 {id} 中)。
我想使用路径 java class.
是否有一种简单而安全的方法来使用 Path class 检索最后一个目录名称?
您可以将 getName()
与可用的 File
一起使用
参考: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());
哪个returns你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
。希望对您有所帮助!
Path#getParent
returns a path’s parent. You can then use Path#getFileName
:
path.getParent().getFileName();
我有一个代表路径的字符串......像这样:
/A/B/C/D/E/{id}/{file_name}.ext
路径结构可能不同,但通常我想检索文件名之前的最后一个目录名(在示例 {id} 中)。
我想使用路径 java class.
是否有一种简单而安全的方法来使用 Path class 检索最后一个目录名称?
您可以将 getName()
与可用的 File
一起使用
参考: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());
哪个returns你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
。希望对您有所帮助!
Path#getParent
returns a path’s parent. You can then use Path#getFileName
:
path.getParent().getFileName();