I have a path to a file stored as a string: "C:\\Users\\Owner\\Desktop\\foo.txt". I want to isolate just the "foo.txt" part, so I try to split the string on a backslash, like so "C:\\Users\\Owner\\Desktop\\foo.txt".split("\\"), then get the last element of the array. If I understand correctly, then the first backslash should escape the second, making it not a special character, so that the string would split on a backslash character. However, when I run the code, I get a java.util.regex.PatternSyntaxException thrown. What is the proper way to split on backslashes in java?
The backslash is reserved, so you have to use a double-backslash like so:
filename.split("\\\\")
To make this solution work consistently across platforms, however, it would be better to use:
filename.split(Pattern.quote(File.separator))
Alternatively, as Dici pointed out, you could just do:
new File(filename).getName()
Oh no... please don't start messing with Windows filenames. One thing you don't want is to have platform-dependent code. Rather than this, use standard Java library:
System.out.println(new File("C:\\Users\\Owner\\Desktop\\foo.txt").getName());
Finally, if you really had to parse the path manually, I would use File.separatorChar to make the code portable.
// hardcoded here for the example, but you would actually get it from somewhere
String path = "C:\\Users\\Owner\\Desktop\\foo.txt";
int i = path.lastIndexOf(File.separatorChar);
String last = i < 0 || i == s.length() ? "" : path.substring(i + 1);
System.out.println(last);
This is also less expensive than splitting a string since you're only interested in the last element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With