'Is there a better to get last element of an absolute path in java?

I have many strings like this D:\just\a\path, the string might differ in number of elements, maybe C:\just\another\longer\path.

I want to get the last element path. I tried using substring:

myString.substring(myString.lastIndexOf("/")+1)

and Path:

nameo1 = Paths.get(string).getName(Paths.get(string).getNameCount() -1); //-1 because of root

but second method seems not to work with all operating system.

My question is: Is there any better, more elegant method to get exactly what I want?

NOTE: the final element is a directory, a folder, not a file. So new File(string).getName() won't work and just return nothing.

Edit: It was my bad. sometimes the string is empty so it return nothing. Cost me an hour working with it. Edit2: Some file paths contain white space, thus this method return an empty string



Solution 1:[1]

You could use String.split:


    String path = "D:\just\a\path";
    String[] directories = path.split("\");
    String last = directories[directories.size-1];

Solution 2:[2]

  public static void main(String[] args) {
    // String str = "C:\\just\\another\\longer\\path\\";
    // String str = "/path/with/right/slashes/works/too/";
       String str = "C:\\and\\path\\with/mixed/slashes/works/too/";

    // String str = "C:\\just\\another\\longer\\path";
    // String str = "/path/with/right/slashes/works/too";
    // String str = "C:\\and\\path\\with/mixed/slashes/works/too";

    String name = Paths.get(str.replace('\\', '/')).toFile().getName();

    System.out.println("name = " + name);

  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kenneth S
Solution 2 ??????? ????????