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?
A file separator is a character that is used to separate directory names that make up a path to a particular location. This character is operating system specific. On Microsoft Windows, it is a back-slash character (), e.g. C:myprojectmyfilesome.
The path separator is a character commonly used by the operating system to separate individual paths in a list of paths.
pathSeparator is used to separate individual file paths in a list of file paths. Consider on windows, the PATH environment variable. You use a ; to separate the file paths so on Windows File.
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];
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