Java file extension without substring

How to get a file extension in Java without using this stupid lastIndexOf('.') Etc.?

+6
source share
4 answers

The Apache Commons library has FilenameUtils.getExtension() .

You can see the source starting here and FilenameUtils .

At least look at their implementation. It's pretty simple, they handle the dir.ext / file file correctly and process something like the file.tar.gz file, you will need a special case if you want to extract .tar.gz, and not just .gz.

+15
source

This is probably the easiest way (also note that depending on the context this is not necessarily correct, for example, ".tar.gz").

You can also split character based string . , and take the last piece, but it's just as difficult.

Is there any special reason why you are trying to avoid substring and lastIndexOf ?

+2
source

Don't want to include external libraries? Use regular expressions:

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

With guava

Files.getFileExtension("some.txt")

0
source

Source: https://habr.com/ru/post/921090/


All Articles