Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting filenames using system file separator symbol

Tags:

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?

like image 318
Vitaly Olegovitch Avatar asked Apr 26 '12 15:04

Vitaly Olegovitch


People also ask

How do I use a file separator?

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.

What is file path separator?

The path separator is a character commonly used by the operating system to separate individual paths in a list of paths.

What is path separator in Java?

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.


2 Answers

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(); 
like image 131
Jon Skeet Avatar answered Oct 27 '22 00:10

Jon Skeet


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]; 
like image 35
Gilbert Le Blanc Avatar answered Oct 27 '22 01:10

Gilbert Le Blanc