Java IO Tutorial

How to get file extension in Java

This article shows how to get the file extension of a file in Java.

Topics

  1. Get file extension normal
  2. Get file extension strict
  3. Get file extension hardcode
  4. Apache Common IO – FilenameUtils

  Path: /path/foo.txt                  -> File Extension: txt
  Path: .                              -> File Extension:
  Path: ..                             -> File Extension:
  Path: /path/run.exe                  -> File Extension: exe
  Path: /path/makefile                 -> File Extension:
  Path: /path/.htaccess                -> File Extension: htaccess
  Path: /path/.tar.gz                  -> File Extension: gz
  Path: /path/../makefile              -> File Extension:
  Path: /path/dir.test/makefile        -> File Extension:

Review the above output from the Get file extension strict example. For a file that has no extension, we will display empty.

1. Get file extension, normal version.

This example shows how to use String#lastIndexOf to get the file extension of a file, and it should fit in most cases.


  String extension = "";

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

However, the above method will fail for the following cases: the directory name or file path contains a dot or double dots, AND the file has no extension.


  Path: /path/../makefile              -> File Extension: /makefile
  Path: /path/dir.test/makefile        -> File Extension: test/makefile

Full example.

GetFileExtension1.java

package com.mkyong.io.howto;

public class GetFileExtension1 {

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";

    public static void main(String[] args) {

        String[] files = {
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
            String output = String.format(OUTPUT_FORMAT, file, getFileExtension(file));
            System.out.println(output);
        }

    }

    /**
     * Fail for below cases
     * <p>
     * "/path/../makefile",
     * "/path/dir.test/makefile"
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null) {
            throw new IllegalArgumentException("fileName must not be null!");
        }

        String extension = "";

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

        return extension;

    }

}

Output

Terminal

Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension:
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: gz
Path: /path/../makefile              -> File Extension: /makefile
Path: /path/dir.test/makefile        -> File Extension: test/makefile

2. Get file extension, strict version.

This example implements extra checking for the directory contains a dot, and the file has no extension.


  Path: /path/../makefile              -> File Extension:
  Path: /path/dir.test/makefile        -> File Extension:

The extra checking ensures the last file extension index (position) is always after the last file separator (Windows or Unix).


  if (indexOfLastExtension > indexOflastSeparator) {
      extension = fileName.substring(indexOfLastExtension + 1);
  }

Full example.

GetFileExtension2.java

package com.mkyong.io.howto;

import java.util.Map;

public class GetFileExtension2 {

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";
    private static final String WINDOWS_FILE_SEPARATOR = "\\";
    private static final String UNIX_FILE_SEPARATOR = "/";
    private static final String FILE_EXTENSION = ".";

    public static void main(String[] args) {

        String[] files = {
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
            String output = String.format(OUTPUT_FORMAT, file, getFileExtensionImproved(file));
            System.out.println(output);
        }

    }

    /**
     * Add extra checking for below cases
     * <p>
     * "/path/../makefile",
     * "/path/dir.test/makefile"
     */
    public static String getFileExtensionImproved(String fileName) {

        if (fileName == null) {
            throw new IllegalArgumentException("fileName must not be null!");
        }

        String extension = "";

        int indexOfLastExtension = fileName.lastIndexOf(FILE_EXTENSION);

        // check last file separator, windows and unix
        int lastSeparatorPosWindows = fileName.lastIndexOf(WINDOWS_FILE_SEPARATOR);
        int lastSeparatorPosUnix = fileName.lastIndexOf(UNIX_FILE_SEPARATOR);

        // takes the greater of the two values, which mean last file separator
        int indexOflastSeparator = Math.max(lastSeparatorPosWindows, lastSeparatorPosUnix);

        // make sure the file extension appear after the last file separator
        if (indexOfLastExtension > indexOflastSeparator) {
            extension = fileName.substring(indexOfLastExtension + 1);
        }

        return extension;

    }

}

Output

Terminal

Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension:
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: gz
Path: /path/../makefile              -> File Extension:
Path: /path/dir.test/makefile        -> File Extension:

3. Get file extension, hardcode version

This example shows how to hardcode some file extensions and display the predefined result. For example, for file extension .tar.gz, we want to display tar.gz, not gz.

GetFileExtension3.java

package com.mkyong.io.howto;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class GetFileExtension3 {

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";
    private static final String WINDOWS_FILE_SEPARATOR = "\\";
    private static final String UNIX_FILE_SEPARATOR = "/";
    private static final String FILE_EXTENSION = ".";
    private static final Map<String, String> KNOWN_EXTENSION = createKnownExtensionMap();

    public static void main(String[] args) {

        String[] files = {
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
            String output = String.format(OUTPUT_FORMAT, file, getFileExtensionKnownExtension(file));
            System.out.println(output);
        }

    }

    public static String getFileExtensionImproved(String fileName) {

        if (fileName == null) {
            throw new IllegalArgumentException("fileName must not be null!");
        }

        String extension = "";

        int indexOfLastExtension = fileName.lastIndexOf(FILE_EXTENSION);

        int indexOflastSeparator = Math.max(
              fileName.lastIndexOf(WINDOWS_FILE_SEPARATOR),
              fileName.lastIndexOf(UNIX_FILE_SEPARATOR)
        );

        if (indexOfLastExtension > indexOflastSeparator) {
            extension = fileName.substring(indexOfLastExtension + 1);
        }

        return extension;

    }

    // hardcoded
    public static String getFileExtensionKnownExtension(final String fileName) {

        if (fileName == null) {
            throw new IllegalArgumentException("fileName must not be null!");
        }

        // if the file name is end with the hard coded extension.
        // Java 8 stream, loop map if key matches get value
        String extension = KNOWN_EXTENSION
                .entrySet()
                .stream()
                .filter(x -> fileName.endsWith(x.getKey()))
                .map(x -> x.getValue())
                .collect(Collectors.joining());

        if ("".equals(extension)) {
            extension = getFileExtensionImproved(fileName); // see example 2
        }

        return extension;

    }

    private static Map<String, String> createKnownExtensionMap() {
        Map<String, String> result = new HashMap<>();
        result.put(".tar.gz", "tar.gz");    // if .tar.gz, gets tar.gz
        result.put("makefile", "make");     // if makefile, get make
        //...extra
        return result;
    }

}

Output

Terminal

Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension: make
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: tar.gz
Path: /path/../makefile              -> File Extension: make
Path: /path/dir.test/makefile        -> File Extension: make

4. Apache Common IO

For Apache commons-io, we can use FilenameUtils.getExtension(fileName) to get the file extension of a file.

pom.xml

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

Full example.

GetFileExtension4.java

package com.mkyong.io.howto;

import org.apache.commons.io.FilenameUtils;

public class GetFileExtension4 {

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";

    public static void main(String[] args) {

        String[] files = {
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
            String output = String.format(OUTPUT_FORMAT, file, FilenameUtils.getExtension(fileName));
            System.out.println(output);
        }

    }

}

Output

Terminal

Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension:
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: gz
Path: /path/../makefile              -> File Extension:
Path: /path/dir.test/makefile        -> File Extension:

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments