Java File Name Get getFileName(File file)

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

Description

get File Name

License

Open Source License

Parameter

Parameter Description
file a parameter

Return

file name without type
for example:
the file name is "example.txt" then the return sub string is "example"

Declaration

public static String getFileName(File file) 

Method Source Code


//package com.java2s;

import java.io.File;

public class Main {
    public static final String FILE_TYPE_FOLDER = "dir";

    /**/*from w ww . ja v a  2s  . c  om*/
     * 
     * @param file
     * @return file name without type<br>
     *         for example:<br>
     *         the file name is "example.txt" then the return sub string is "example"
     */
    public static String getFileName(File file) {
        if (file.isDirectory()) {
            return file.getName();
        } else {
            String fileType = getFileType(file);
            if ("unknown".equals(fileType)) {
                return file.getName();
            } else {
                String fileName = file.getName();
                // "-1" in order to drop the "."
                return fileName.substring(0, fileName.length() - fileType.length() - 1);
            }
        }

    }

    /**
     * 
     * @param file
     * @return the file type like "exe"
     */
    public static String getFileType(File file) {
        if (file.isDirectory()) {
            return FILE_TYPE_FOLDER;
        } else {
            String[] strArray = file.getName().split("\\.");

            int length = strArray.length;
            if (length > 1) {
                return strArray[length - 1];

            } else {
                return "unknown";
            }
        }
    }
}

Related

  1. getFileName(File file)
  2. getFilename(File file)
  3. getFilename(File file)
  4. getFilename(File file)
  5. getFileName(File file)
  6. getFileName(File file)
  7. getFilename(File file, boolean withExtension)
  8. getFileName(File path)
  9. getFileName(final File file)