Java File Name Get getFilename(File file, boolean withExtension)

Here you can find the source of getFilename(File file, boolean withExtension)

Description

get Filename

License

Open Source License

Declaration

public static String getFilename(File file, boolean withExtension) 

Method Source Code


//package com.java2s;
/* /*from  ww w  .  j a  v  a2  s .c o m*/
 * RealmSpeak is the Java application for playing the board game Magic Realm.
 * Copyright (c) 2005-2015 Robin Warren
 * E-mail: robin@dewkid.com
 * 
 * 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 3 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, see
 *
 * http://www.gnu.org/licenses/
 */

import java.io.*;

public class Main {
    private static final int PATH = 0;
    private static final int FILENAME = 1;
    private static final int EXTENSION = 2;

    public static String getFilename(File file, boolean withExtension) {
        String[] piece = _splitPathName(file);
        if (withExtension) {
            return piece[FILENAME] + piece[EXTENSION];
        }
        return piece[FILENAME];
    }

    private static String[] _splitPathName(File file) {
        String totalPath = file.getAbsolutePath();
        int sIndex = totalPath.lastIndexOf(File.separator);
        if (sIndex >= 0) {
            String[] piece = new String[3]; // path - filename - ext
            String pathOnly = totalPath.substring(0, sIndex) + File.separator;
            piece[PATH] = pathOnly;
            String filename = totalPath.substring(sIndex + 1);
            int eIndex = filename.lastIndexOf(".");
            piece[FILENAME] = eIndex < 0 ? filename : filename.substring(0, eIndex);
            piece[EXTENSION] = eIndex < 0 ? "" : filename.substring(eIndex);
            return piece;
        }
        return null;
    }
}

Related

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