Java File Extension Name Extract getFileExtension(File file)

Here you can find the source of getFileExtension(File file)

Description

returns a file's extension/type, excluding the extension separator (by default a period '.')

License

Open Source License

Parameter

Parameter Description
file the file name with extension

Return

the file extension as a string or null if the file extension cannot be identified

Declaration

public static final String getFileExtension(File file) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

public class Main {
    /** returns a file's extension/type, excluding the extension separator (by default a period '.')
     * @param file the file name with extension
     * @return the file extension as a string or null if the file extension cannot be identified
     *//*from  w  w  w  .j  a va2  s  . c om*/
    public static final String getFileExtension(File file) {
        return getFileExtension(file.getName());
    }

    /** returns a file's extension/type, excluding the extension separator (by default a period '.')
     * @param filepath the file name with extension
     * @return the file extension as a string or empty string if the file extension cannot be identified
     */
    public static final String getFileExtension(String filepath) {
        // Get the file type by getting the sub string starting at the last index of '.'
        int dotIdx = -1;
        int separatorIdx = -1;
        int fileLen = filepath.length();
        for (int i = fileLen - 1; i > -1; i--) {
            char ch = filepath.charAt(i);
            // last '.' dot index
            if (dotIdx < 0 && ch == '.') {
                dotIdx = i;
            }
            // break on last separator
            if (ch == '/' || ch == '\\') {
                separatorIdx = i;
                break;
            }
        }

        return fileLen <= dotIdx + 1 || dotIdx < separatorIdx ? "" : filepath.substring(dotIdx + 1); // Return the ending substring
    }
}

Related

  1. getFileExtension(File file)
  2. getFileExtension(File file)
  3. getFileExtension(File file)
  4. getFileExtension(File file)
  5. getFileExtension(File file)
  6. getFileExtension(File file)
  7. getFileExtension(File file)
  8. getFileExtension(File file)
  9. getFileExtension(File file)