Java File Extension Name Get getFileExtension(final File aFile)

Here you can find the source of getFileExtension(final File aFile)

Description

Returns the "presumed" filename extension (like '.jpg', '.zip') from a given file.

License

Open Source License

Parameter

Parameter Description
aFile the file to return the extension for, cannot be <code>null</code>.

Return

the file extension (always in lower case), never null but can be empty if the given file has no file extension.

Declaration

public static final String getFileExtension(final File aFile) 

Method Source Code


//package com.java2s;
/*//from   w  w  w  .jav  a2  s .  c o  m
 * OpenBench LogicSniffer / SUMP project
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *
 * 
 * Copyright (C) 2010-2011 - J.W. Janssen, http://www.lxtreme.nl
 */

import java.io.*;

public class Main {
    /**
     * Returns the "presumed" filename extension (like '.jpg', '.zip') from a
     * given file.
     * 
     * @param aFile
     *          the file to return the extension for, cannot be <code>null</code>.
     * @return the file extension (always in lower case), never <code>null</code>
     *         but can be empty if the given file has <em>no</em> file extension.
     */
    public static final String getFileExtension(final File aFile) {
        String ext = "";

        String filename = aFile.getName();
        int idx = filename.lastIndexOf('.');

        if ((idx >= 0) && (idx < (filename.length() - 1))) {
            ext = filename.substring(idx + 1).toLowerCase();
        }

        // Avoid directories being detected as having a file extension...
        if (aFile.exists() && aFile.isDirectory() && !"".equals(ext)) {
            ext = "";
        }

        return ext;
    }
}

Related

  1. getFileExtension(File file)
  2. getFileExtension(File file)
  3. getFileExtension(File file)
  4. getFileExtension(File file, boolean includeDot)
  5. getFileExtension(File file, boolean withDot)
  6. getFileExtension(final File file)
  7. getFileExtension(final File file)
  8. getFileExtension(final String file)
  9. getFileExtension(final String fullName)