Java File Extension Name Extract getFileExtension(String filename)

Here you can find the source of getFileExtension(String filename)

Description

get File Extension

License

Apache License

Declaration

public static String getFileExtension(String filename) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;

public class Main {

    public static String getFileExtension(String filename) {
        // returns extension including .
        // Now strip of possible extension.

        String extension = "";
        int index = filename.lastIndexOf('.');
        if (index != -1)
            extension = filename.substring(index);

        return extension;
    }/*from   w w w  .ja  v a  2  s. c o m*/

    public static String getFileExtension(File file) {
        // returns extension including .

        // Strip of path first.
        String base = file.getName();
        // Now strip of possible extension.

        String extension = "";
        int index = base.lastIndexOf('.');
        if (index != -1)
            extension = base.substring(index);

        return extension;
    }

    public static String getFileExtension(String filename, boolean keepDot) {
        filename = filename.replace('\\', '/');

        String name;
        int namePos = filename.lastIndexOf('/');
        if (namePos != -1) {
            name = filename.substring(namePos + 1);
        } else {
            // no path info found
            name = filename;
        }

        String ext;
        int extPos = name.lastIndexOf('.');
        if (extPos != -1) {
            if (keepDot)
                ext = name.substring(extPos);
            else
                ext = name.substring(extPos + 1);
        } else {
            // no extension found
            ext = "";
        }

        return ext;
    }

    public static String getFileExtension(File file, boolean keepDot) {
        // Strip path first.
        String base = file.getName();

        String extension = "";
        int index = base.lastIndexOf('.');
        if (index != -1) {
            if (keepDot)
                extension = base.substring(index);
            else
                extension = base.substring(index + 1);
        }
        return extension;
    }
}

Related

  1. getFileExtension(File file, boolean includeDelimiter)
  2. getFileExtension(File fx)
  3. getFileExtension(File path)
  4. getFileExtension(final String fileName)
  5. getFileExtension(final String filenamePath)
  6. getFileExtension(String fileName)
  7. getFileExtension(String filename, String extensionSeparator)
  8. getFileExtension(String filePath)
  9. getFileExtensionIgnoringGz(File f)