Java - How to get file extension from file

You can get extension from File name in Java.

Get extension by file name

You can think of the last . in the file name as shown below and the string after it as the extension.

File file = new File("/home/js/test/myfile/file1.txt");
String fileName = file.getName();
String ext = fileName.substring(fileName.lastIndexOf(".") + 1);

System.out.println("file name : " + fileName);
System.out.println("extension : " + ext);

result

file name : file1.txt
extension : txt

How to use Stream

You can also get the extension using Optional and Stream.

The following code gets the extension and Optional<String>.

File file = new File("/home/js/test/myfile/file1.txt");
String fileName = file.getName();
Optional<String> ext = getExtensionByStringHandling(fileName);
ext.ifPresent(s -> System.out.println("extension : " + s));


public static Optional<String> getExtensionByStringHandling(String filename) {
    return Optional.ofNullable(filename)
            .filter(f -> f.contains("."))
            .map(f -> f.substring(filename.lastIndexOf(".") + 1));
}

If the file is a folder, it has no extension. In this case, Optional will be null. If there is an extension like file1.txt, Optional will have a String.

Import extension using Commons-io library

You can easily get the extension by using FilenameUtils.getExtension() of the Commons-io library.

To use Commons-io, in the case of a Gradle project, add the following to dependencies of build.gradle.

dependencies {
  compile group: 'commons-io', name: 'commons-io', version: '2.6'
  ...
}

For projects that use other build systems such as Maven, refer to mvnrepository.com and configure it.

The following example is the code to get the extension with FilenameUtils.

System.out.println();
File file = new File("/home/js/test/myfile/file1.txt");
String fileName = file.getName();
String ext = FilenameUtils.getExtension(fileName);
System.out.println("extension : " + ext);

If there is no extension such as a folder, an empty string ("") is returned instead of null.

Reference

codechachaCopyright ©2019 codechacha