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?

Community
  • 1
  • 1
Sandeep Johal
  • 399
  • 2
  • 6
  • 16

3 Answers3

2
String filenameSansExt = filename.replaceAll("\\.[^.]*", "");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
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().

andr
  • 15,970
  • 10
  • 45
  • 59
yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
-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);
carloabelli
  • 4,289
  • 3
  • 43
  • 70
  • what happens when there is no extension or the extension is longer than 3 characters + a `.`? Not to mention filenames that are < 4 characters? –  Jan 13 '13 at 02:12