Java File Name Get getFileName(File f)

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

Description

Return the file name without path or extension.

License

Open Source License

Parameter

Parameter Description
f The file

Return

The file name with no path or extension

Declaration

public static String getFileName(File f) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 Firestar Software, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  w ww.j  a  v  a  2s . co  m
 *     Firestar Software, Inc. - initial API and implementation
 *
 * Author:
 *     Gabriel Oancea
 *
 *******************************************************************************/

import java.io.*;

public class Main {
    /**
     * Return the file name without path or extension. If the file is one of the special '.', '..' will return it as
     * such. If the file name begins with '.' return it as such. Otherwise will remove the last '.' and anything
     * following after it. For example:
     * 
     * <pre>
     * <p><code>File Name       Returned value</code>
     * <p><code>null            null </code>
     * <p><code>"."             "." </code>
     * <p><code>".."            ".." </code>
     * <p><code>".hidden"       ".hidden" </code>
     * <p><code>"some"          "some" </code>
     * <p><code>"some.txt"      "some" </code>
     * <p><code>"some.file.txt" "some.file" </code>
     * </pre>
     * 
     * No checks are made if the file exists, or is a file/directory, etc.
     * 
     * @param f The file
     * @return The file name with no path or extension
     */
    public static String getFileName(File f) {
        if (f == null)
            return null;
        String fn = f.getName();
        if (fn.length() <= 0 || fn.equals(".") || fn.equals(".."))
            return fn;
        int p = fn.lastIndexOf('.');
        if (p < 0)
            return fn;
        if (p == 0)
            return "";
        return fn.substring(0, p);
    }
}

Related

  1. getFileName(Class cls, String ext)
  2. getFileName(File element)
  3. getFileName(File f)
  4. getFileName(File f)
  5. getFileName(File file)
  6. getFileName(File file)
  7. getFileName(File file)