6

How do I get file extension in Java without using that silly lastIndexOf('.') etc.?

4
  • possible duplicate of How do I trim a file extension from a String in Java? Commented Jul 22, 2012 at 20:23
  • possible not. Any solution there is using lastIndexOf Commented Jul 22, 2012 at 20:57
  • 1
    A little background into why lastindexof isn't what you want or isn't working for you - sure I know this is approach has issues as well, but a little understanding as to why you are looking for another approach might help. Commented Jul 22, 2012 at 21:08
  • I guess the other libraries also would follow the same method. In fact FileNameUtils use the same mechanism. But i wonder why you dont want that. Do you think it will fail for some cases. If so can u state an example of failure with this case? Commented Jan 29, 2014 at 7:13

4 Answers 4

15

The apache Commons library has FilenameUtils.getExtension().

You can look over the source starting here, and FilenameUtils.

At least look over their implementation. It's pretty simple, they handle dir.ext/file correctly, and to handle something like file.tar.gz you'll need a special case if you want to extract .tar.gz rather than just .gz.

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

3 Comments

I had interpreted that he wanted the file extension itself, not the name without the extension. There is still a method for that (getExtension), but read what it does: "returns the textual part of the filename after the last dot." That's exactly what he's already doing; there's no point in adding an entire library/dependency just for the same functionality (unless he's already using Apache Commons).
@JonathanNewmuis that is, right about my method mixup. I believe that the implementation of getExtension is a bit more thorough that simply wrapping a lastIndexOf, for reasons that your own answer addresses, and e.g. dir.ext/file.
Unfortunately this is not a standard library, so it is overkill for the probblem, i used lastIndexOf
2

That's probably the easiest way (also note that depending on the context, it's not necessarily correct, e.g. ".tar.gz").

You could also split the string based on the . character and take the last piece, but that seems just as difficult.

Is there a particular reason why you're trying to avoid substring and lastIndexOf?

Comments

1

Do not want to include external libraries? Use regular expressions:

String extension = filename.replaceAll("^.*\\.([^.]+)$", "$1"); 

Comments

0

With guava

Files.getFileExtension("some.txt")

2 Comments

I am afraid there is no such method in jdk8, I guess you mean google's guava
@A4L thanks for pointing this out, I got confused by java.lang package of this class ☺

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.