Splitting filenames using system file separator symbol Splitting filenames using system file separator symbol windows windows

Splitting filenames using system file separator symbol


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();


When you write a file name, you should use System.getProperty("file.separator").

When you read a file name, you could possibly have either the forward slash or the backward slash as a file separator.

You might want to try the following:

fileName = fileName.replace("\\", "/");String[] splittedFileName = fileName.split("/"));String simpleFileName = splittedFileName[splittedFileName.length-1];


First of all, for this specific problem I'd recommend using the java.util.File class instead of a regex.

That being said, the root of the problem you're running into is that the backslash character '\' signifies an escape sequence in Java regular expressions. What's happening is the regex parser is seeing the backslash and expecting there to be another character after it which would complete the escape sequence. The easiest way to get around this is to use the java.util.regex.Pattern.quote() method which will escape any special characters in the string you give it.

With this change your code becomes:

String splitRegex = Pattern.quote(System.getProperty("file.separator"));String[] splittedFileName = fileName.split(splitRegex);String simpleFileName = splittedFileName[splittedFileName.length-1];