001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *   http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 */
018
019package org.apache.commons.compress.utils;
020
021import java.io.File;
022
023/**
024 * Generic file name utilities.
025 * @since 1.20
026 */
027public class FileNameUtils {
028
029    /**
030     * Returns the extension (i.e. the part after the last ".") of a file.
031     *
032     * <p>Will return an empty string if the file name doesn't contain
033     * any dots. Only the last segment of a the file name is consulted
034     * - i.e. all leading directories of the {@code filename}
035     * parameter are skipped.</p>
036     *
037     * @return the extension of filename
038     * @param filename the name of the file to obtain the extension of.
039     */
040    public static String getExtension(String filename) {
041        if (filename == null) {
042            return null;
043        }
044
045        String name = new File(filename).getName();
046        int extensionPosition = name.lastIndexOf('.');
047        if (extensionPosition < 0) {
048            return "";
049        }
050        return name.substring(extensionPosition + 1);
051    }
052
053    /**
054     * Returns the basename (i.e. the part up to and not including the
055     * last ".") of the last path segment of a filename.
056     *
057     * <p>Will return the file name itself if it doesn't contain any
058     * dots. All leading directories of the {@code filename} parameter
059     * are skipped.</p>
060     *
061     * @return the basename of filename
062     * @param filename the name of the file to obtain the basename of.
063     */
064    public static String getBaseName(String filename) {
065        if (filename == null) {
066            return null;
067        }
068
069        String name = new File(filename).getName();
070
071        int extensionPosition = name.lastIndexOf('.');
072        if (extensionPosition < 0) {
073            return name;
074        }
075
076        return name.substring(0, extensionPosition);
077    }
078}