Java File Extension Name Extract getFileExtension(File file)

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

Description

Utility method that gets the extension of a file from its name if it has one

License

Mozilla Public License

Declaration

public static String getFileExtension(File file) 

Method Source Code


//package com.java2s;
/* SpagoBI, the Open Source Business Intelligence suite
    /*from  w  w w . j  av  a  2  s  . c o  m*/
 * Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice. 
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import java.io.File;
import java.io.IOException;

public class Main {
    /**
     * Utility method that gets the extension of a file from its name if it has one
     */
    public static String getFileExtension(File file) {
        try {
            return getFileExtension(file.getCanonicalPath());
        } catch (IOException e) {
            return "";
        }
    }

    /**
      * Utility method that gets the extension of a file from its name if it has one
      */
    public static String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") < 0) {
            return "";
        }

        // Could be that the file name actually end with a '.' so lets check
        if (fileName.lastIndexOf(".") + 1 == fileName.length()) {
            return "";
        }

        String extension = fileName.substring(fileName.lastIndexOf(".") + 1);

        // Could be that the path actually had a '.' in it so lets check
        if (extension.contains(File.separator)) {
            extension = "";
        }

        return extension;
    }
}

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, boolean includeDelimiter)
  9. getFileExtension(File fx)