svz
svz

Reputation: 4588

Java: parsing file path

I need to parse a file path to get the filename from it. What confuses me is that windows uses \ as the delimeter and linux - / and somehow the provided filepath can even contain both delimeters at the same time.

Of course I can do:

int slash = filePath.lastIndexOf("/");
int backslash = filePath.lastIndexOf("\\");
fileName = filePath.substring(slash > backslash ? slash : backslash);

but is there a better way in case I have more delimiters? (probably not for a file path)

Upvotes: 3

Views: 11929

Answers (2)

LuigiEdlCarno
LuigiEdlCarno

Reputation: 2415

You can use

String separator =System.getProperty("path.separator");

to get you systems separator.

Upvotes: 0

Duncan Jones
Duncan Jones

Reputation: 69410

Just use the File class:

String fileName = new File(path).getName();

It handles forward and backwards slashes, plus combinations of the two.

Upvotes: 9

Related Questions