有没有更好的方法来获取java中绝对路径的最后一个元素?

Hùn*_*yễn 6 java path

我有很多这样的字符串D:\just\a\path,字符串的元素数量可能有所不同,也许C:\just\another\longer\path

我想得到最后一个元素path。我尝试使用substring

myString.substring(myString.lastIndexOf("/")+1)
Run Code Online (Sandbox Code Playgroud)

Path

nameo1 = Paths.get(string).getName(Paths.get(string).getNameCount() -1); //-1 because of root
Run Code Online (Sandbox Code Playgroud)

但第二种方法似乎不适用于所有操作系统。

我的问题是:有没有更好、更优雅的方法来得到我想要的东西?

注意:最后一个元素是目录、文件夹,而不是文件。所以new File(string).getName()不会工作,只是返回任何东西。

编辑:这是我的错。有时字符串为空,因此不会返回任何内容。我花了一个小时来处理它。Edit2:某些文件路径包含空格,因此此方法返回空字符串

deH*_*aar 7

您可以(现在应该)使用java.nio.file.Path.getFileName(),它对于文件或目录的路径如下所示(无论是否String以反斜杠结尾):

public static void main(String[] args) {
    String pathStringToAFile = "U:\\temp\\TestOutput\\TestFolder\\test_file.txt";
    String pathStringToAFolder = "U:\\temp\\TestOutput\\TestFolder";
    String pathStringToAFolderWithTrailingBackslash = "U:\\temp\\TestOutput\\TestFolder\\";

    Path pathToAFile = Paths.get(pathStringToAFile);
    Path pathToAFolder = Paths.get(pathStringToAFolder);
    Path pathToAFolderWithTrailingBackslash 
                        = Paths.get(pathStringToAFolderWithTrailingBackslash);

    System.out.println(pathToAFile.getFileName().toString());
    System.out.println(pathToAFolder.getFileName().toString());
    System.out.println(pathToAFolderWithTrailingBackslash.getFileName().toString());
}
Run Code Online (Sandbox Code Playgroud)

这输出

public static void main(String[] args) {
    String pathStringToAFile = "U:\\temp\\TestOutput\\TestFolder\\test_file.txt";
    String pathStringToAFolder = "U:\\temp\\TestOutput\\TestFolder";
    String pathStringToAFolderWithTrailingBackslash = "U:\\temp\\TestOutput\\TestFolder\\";

    Path pathToAFile = Paths.get(pathStringToAFile);
    Path pathToAFolder = Paths.get(pathStringToAFolder);
    Path pathToAFolderWithTrailingBackslash 
                        = Paths.get(pathStringToAFolderWithTrailingBackslash);

    System.out.println(pathToAFile.getFileName().toString());
    System.out.println(pathToAFolder.getFileName().toString());
    System.out.println(pathToAFolderWithTrailingBackslash.getFileName().toString());
}
Run Code Online (Sandbox Code Playgroud)