0

Possible Duplicate:
How to get file name without the extension?

I have a list of xml files and I'm trying to return just the file name without the extension. For example, if I have:

String filename = "hello.xml"; 

How would I return just "hello" with the fact the file names vary?

0

3 Answers 3

2
String filenameSansExt = filename.replaceAll("\\.[^.]*", ""); 
Sign up to request clarification or add additional context in comments.

Comments

1

Using substring() is more efficient rather than using replaceAll() with regex, or any other regex.

Both answers are not quite satisfactory:

  • regex is too slow, but correct
  • lastIndexOf() will throw an exception when '.' is not there (index -1)

Correct answer has to check index of lastIndexOf().

Comments

-1

You can use the substring function for strings in java. You would start at 0 (the beginning of the string) and end before the 4th to last character (".")

String filename = "hello.xml"; String filename2 = filename.substring(0, filename.length() - 4); 

1 Comment

what happens when there is no extension or the extension is longer than 3 characters + a .? Not to mention filenames that are < 4 characters?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.