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

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


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):

import org.apache.commons.io.FilenameUtils;// ...String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"

Maven dependency:

<dependency>  <groupId>commons-io</groupId>  <artifactId>commons-io</artifactId>  <version>2.6</version></dependency>

Gradle Groovy DSL

implementation 'commons-io:commons-io:2.6'

Gradle Kotlin DSL

implementation("commons-io:commons-io:2.6")

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


Do you really need a "parser" for this?

String extension = "";int i = fileName.lastIndexOf('.');if (i > 0) {    extension = fileName.substring(i+1);}

Assuming that you're dealing with simple Windows-like file names, not something like archive.tar.gz.

Btw, for the case that a directory may have a '.', but the filename itself doesn't (like /path/to.a/file), you can do

String extension = "";int i = fileName.lastIndexOf('.');int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));if (i > p) {    extension = fileName.substring(i+1);}


private String getFileExtension(File file) {    String name = file.getName();    int lastIndexOf = name.lastIndexOf(".");    if (lastIndexOf == -1) {        return ""; // empty extension    }    return name.substring(lastIndexOf);}