Splitting filenames using system file separator symbol
file-io, java, regex, windows
Solution
The problem is that `\` has to be escaped in order to use it as backslash within a regular expression. You should either use a splitting API which doesn't use regular expressions, or use `Pattern.quote` first:
// Alternative: use Pattern.quote(File.separator)
String pattern = Pattern.quote(System.getProperty("file.separator"));
String[] splittedFileName = fileName.split(pattern);
Or even better, use the `File` API for this:
File file = new File(fileName);
String simpleFileName = file.getName();
Problem
I have a complete file path and I want to get the file name. I am using the following instruction: ``` String[] splittedFileName = fileName.split(System.getProperty("file.separator")); String simpleFileName = splittedFileName[splittedFileName.length-1]; ``` But on Windows it gives: ``` java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \ ^ ``` Can I avoid this exception? Is there a better way to do this?