3

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)

1
  • 3
    File f = new File(fileName); String name = f.getName(); Commented Jun 10, 2013 at 10:36

2 Answers 2

9

Just use the File class:

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

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can use

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

to get you systems separator.

1 Comment

This won't do as there may be both separators at the same time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.