Skip to content
Advertisement

How do I get the file extension of a file in Java?

Just to be clear, I’m not looking for the MIME type.

Let’s say I have the following input: /path/to/file/foo.txt

I’d like a way to break this input up, specifically into .txt for the extension. Is there any built in way to do this in Java? I would like to avoid writing my own parser.

Advertisement

Answer

In this case, use FilenameUtils.getExtension from Apache Commons IO

Here is an example of how to use it (you may specify either full path or just file name):

JavaScript

Maven dependency:

JavaScript

Gradle Groovy DSL

JavaScript

Gradle Kotlin DSL

JavaScript

Others https://search.maven.org/artifact/commons-io/commons-io/2.6/jar

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement