Yoda
Yoda

Reputation: 18068

Java getting file extension without substring

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

Upvotes: 6

Views: 20005

Answers (4)

Entea
Entea

Reputation: 957

With guava

Files.getFileExtension("some.txt")

Upvotes: 0

Paul Vargas
Paul Vargas

Reputation: 42020

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

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

Upvotes: 1

pb2q
pb2q

Reputation: 59617

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.

Upvotes: 15

Jon Newmuis
Jon Newmuis

Reputation: 26502

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?

Upvotes: 2

Related Questions