Java File Extension Name Extract getFileExtension(File file, boolean includeDelimiter)

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

Description

Return the extension part given file name.

License

BSD License

Parameter

Parameter Description
file a parameter
includeDelimiter a parameter

Return

the extension or an empty string if nothing is found

Declaration

public static final String getFileExtension(File file, boolean includeDelimiter) 

Method Source Code

//package com.java2s;
/*L//  w ww. j a  v  a2  s  . co m
 * Copyright SAIC, SAIC-Frederick.
 *
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/caadapter/LICENSE.txt for details.
 */

import java.io.*;

public class Main {
    /**
     * Return the extension part given file name.
     * For example, if the name of the file is "foo.bar", ".bar" will be returned
     * if includeDelimiter is true, or "bar" will be returned if includeDelimiter is false;
     * otherwise, if no extension is specified in the file name, empty string is
     * returned instead of null.
     *
     * @param file
     * @param includeDelimiter
     * @return the extension or an empty string if nothing is found
     */
    public static final String getFileExtension(File file, boolean includeDelimiter) {
        String result = "";
        if (file != null) {
            String absoluteName = file.getAbsolutePath();
            if (absoluteName != null) {
                int delimIndex = absoluteName.lastIndexOf(".");
                if (delimIndex != -1) {//include the . delimiter
                    if (!includeDelimiter) {//skip the . delimiter
                        delimIndex++;
                    }
                    result = absoluteName.substring(delimIndex);
                }
            }
        }
        return result;
    }
}

Related

  1. getFileExtension(File file)
  2. getFileExtension(File file)
  3. getFileExtension(File file)
  4. getFileExtension(File file)
  5. getFileExtension(File file)
  6. getFileExtension(File fx)
  7. getFileExtension(File path)
  8. getFileExtension(final String fileName)
  9. getFileExtension(final String filenamePath)