Java File Name Get getFileNameWithoutExtension(final File file)

Here you can find the source of getFileNameWithoutExtension(final File file)

Description

Returns file name without the extension.

License

Apache License

Parameter

Parameter Description
file Input file

Return

File name without extension

Declaration

public static String getFileNameWithoutExtension(final File file) 

Method Source Code

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

import java.io.*;

public class Main {
    public static final String[] NO_EXTENSIONS = new String[] {};

    /**//w  w w .jav a2  s  . com
     * Returns file name without the extension. Extension being everything beyond the last dot.
     * Example:
     * <pre>
     * a/b/c/foo.txt --> foo
     * </pre>
     *
     * @param file Input file
     * @return File name without extension
     */
    public static String getFileNameWithoutExtension(final File file) {
        if (file == null) {
            return null;
        }
        return stripExtension(file.getName());
    }

    /**
     * Remove extension from filename. ie
     * <pre>
     * foo.txt    --> foo
     * a\b\c.jpg --> a\b\c
     * a\b\c     --> a\b\c
     * </pre>
     *
     * @param filename the filename
     * @return the filename minus extension
     */
    public static String stripExtension(final String filename) {
        return stripExtension(filename, NO_EXTENSIONS);
    }

    /**
     * Remove extension from filename. Support multi-part extensions. If you provide
     * {@code pep.xml} in the extensions parameter, you get the following behavior:
     * <pre>
     *     foo.txt -> foo
     *     foo.bla.xml -> foo.bla
     *     foo.pep.xml -> foo
     * </pre>
     *
     * @param filename   Filename to remove extension from.
     * @param extensions Extra multi-part extensions, such as {@code pep.xml}, to be honored
     * @return the filename minus extension
     */
    public static String stripExtension(final String filename, final String[] extensions) {
        for (final String extension : extensions) {
            if (filename.endsWith("." + extension)) {
                return filename.substring(0, filename.length() - extension.length() - 1);
            }
        }

        final int index = filename.lastIndexOf('.');
        if (-1 == index) {
            return filename;
        } else {
            return filename.substring(0, index);
        }
    }
}

Related

  1. getFileNameWithoutExtension(File file)
  2. getFileNameWithoutExtension(File file)
  3. getFileNameWithoutExtension(File file)
  4. getFileNameWithoutExtension(File fx)
  5. getFilenameWithoutExtension(final File file)
  6. getFilenameWithoutExtension(final String fileName)
  7. getFileNameWithoutExtension(final String filePath)
  8. getFileNameWithoutExtension(String fileName)
  9. getFileNameWithoutExtension(String filePath)