【问题标题】:Retrieve last level directory name from path从路径中检索最后一级目录名称
【发布时间】:2021-05-25 22:05:28
【问题描述】:

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

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

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

我想使用 Path java 类。

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

【问题讨论】:

标签: java parsing path


【解决方案1】:

Path#getParent 返回路径的父级。然后你可以使用Path#getFileName:

path.getParent().getFileName();

【讨论】:

    【解决方案2】:

    您可以将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());
    

    返回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。希望对您有所帮助!

    【讨论】:

    • 他还可以将路径转换为文件对象为new File(path.toString())
    猜你喜欢
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 2015-02-01
    相关资源
    最近更新 更多