Reputation: 629
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
Upvotes: 6
Views: 14170
Reputation: 574
Get last Directory of a path:
Paths.get(path).getParent().getFileName();
Upvotes: 1
Reputation: 18558
You can (and nowadays should) use java.nio.file.Path.getFileName()
, which works like this for paths to files or directories (no matter if the String
ends with a backslash or not):
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());
}
This outputs
test_file.txt
TestFolder
TestFolder
Upvotes: 7
Reputation: 66
You could use String.split:
String path = "D:\just\a\path";
String[] directories = path.split("\");
String last = directories[directories.size-1];
Upvotes: 1
Reputation: 92
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);
}
Upvotes: 0