Extract file name (without path and suffix) from file name with path and suffix. - Java java.io

Java examples for java.io:File Name

Description

Extract file name (without path and suffix) from file name with path and suffix.

Demo Code

/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation.
 * 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:/*  w w  w.ja va 2s.c  o m*/
 *  Actuate Corporation  - initial API and implementation
 ****/
//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String filePathName = "java2s.com";
        System.out.println(extractFileName(filePathName));
    }

    /**
     * Extract file name (without path and suffix) from file name with path and
     * suffix.
     * <p>
     * For example:
     * <p>
     * <ul>
     * <li>"c:\home\abc.xml" => "abc"
     * <li>"c:\home\abc" => "abc"
     * <li>"/home/user/abc.xml" => "abc"
     * <li>"/home/user/abc" => "abc"
     * </ul>
     * 
     * @param filePathName
     *            the file name with path and suffix
     * @return the file name without path and suffix
     */

    public static String extractFileName(String filePathName) {
        if (filePathName == null)
            return null;

        int dotPos = filePathName.lastIndexOf('.');
        int slashPos = filePathName.lastIndexOf('\\');
        if (slashPos == -1)
            slashPos = filePathName.lastIndexOf('/');

        if (dotPos > slashPos) {
            return filePathName.substring(slashPos > 0 ? slashPos + 1 : 0,
                    dotPos);
        }

        return filePathName.substring(slashPos > 0 ? slashPos + 1 : 0);
    }
}

Related Tutorials