java - 从路径中检索最后一级目录名称
问题描述
我有一个代表路径的字符串......像这样:
/A/B/C/D/E/{id}/{file_name}.ext
路径结构可能不同,但通常我想在文件名之前检索最后一个目录名(在示例 {id} 中)。
我想使用 Path java 类。
有没有一种简单安全的方法来使用 Path 类检索最后一个目录名称?
解决方案
您可以使用getName()
with File
which 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
。希望能帮助到你 !
推荐阅读
- c++ - 在 C++ 中重载输入/输出运算符
- presto - 如何从 Eclipse 调试 presto-server?
- c - FPGA模数转换DE1-SOC
- python - 将行附加到空 DataFrame 将 dtype 从 int 转换为 object
- javascript - 联系表格 7 插件定制
- json - 如何以base64编码作为输入处理[]byte(字节数组)
- angular - Angular 4-在每个页面的负载上显示加载器并在所有 API 请求完成后隐藏
- java - hbase Regionserver 启动,zookeeper 启动但 hmaster 没有启动(regionserver.HRegionServer: Failed construction RegionServer)
- c# - InvalidOperationException: 没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme
- c - C编程链表for循环