com.sunchenbin.store.feilong.core.io.FilenameUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.sunchenbin.store.feilong.core.io.FilenameUtil.java

Source

/*
 * Copyright (C) 2008 feilong
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sunchenbin.store.feilong.core.io;

import java.io.File;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunchenbin.store.feilong.core.util.Validator;

/**
 * The Class FilenameUtil.
 *
 * @author feilong
 * @version 1.4.0 201584 ?11:47:18
 * @see org.apache.commons.io.FilenameUtils
 * @since 1.4.0
 */
public final class FilenameUtil {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(FilenameUtil.class);

    /**
     * ???????,?,??? .
     * <p>
     * Windows ?? 255  <br>
     * DOS ,?? 8 ,?? 3 ,? DOS 8.3 ??. <br>
     * ?????,???,???  1 ? ?  C ? . <br>
     * ???
     * </p>
     * <ul>
     * <li>???? 9  \/:*?"<>|</li>
     * <li>??  ?? ? ??.  ?? ?  con , aux , com0 ~ com9 , lpt0 ~ lpt9 , nul , prn</li>
     * <li>????, A.txt  a.TxT ?</li>
     * </ul>
     * 
     * @see <a href="http://support.microsoft.com/kb/177506/zh-cn">? ????</a>
     * @since 1.0.7
     */
    private static final String[][] MICROSOFT_PC = { //
            //            { "\\", "" }, // \
            //  { "/", "" }, // /
            { "\"", "" }, // "
            { ":", "" }, // :
            { "*", "" }, // *
            { "?", "" }, // ?
            { "<", "" }, // <
            { ">", "" }, // >
            { "|", "" }, // |
    };

    /** Don't let anyone instantiate this class. */
    private FilenameUtil() {
        //AssertionError?. ?????. ???.
        //see Effective Java 2nd
        throw new AssertionError("No " + getClass().getName() + " instances for you!");
    }

    /**
     * ??? ???,???.
     * 
     * @param fileName
     *            ??
     * @return ???
     * @see #MICROSOFT_PC
     * @since 1.0.7
     */
    public static String getFormatFileName(final String fileName) {
        String formatFileName = fileName;

        for (int i = 0, j = MICROSOFT_PC.length; i < j; ++i) {
            String[] arrayElement = MICROSOFT_PC[i];

            String oldChar = arrayElement[0];
            String newChar = arrayElement[1];
            if (formatFileName.contains(oldChar)) {
                LOGGER.warn("formatFileName:[{}] contains oldChar:[{}],will replace newChar:[{}]", formatFileName,
                        oldChar, newChar);
                formatFileName = formatFileName.replace(oldChar, newChar);
            }
        }
        return formatFileName;
    }

    /**
     * ???.
     * 
     * <p>
     * :F:/pie2.png,return pie2.png
     * </p>
     * 
     * @param fileName
     *            the file name
     * @return the file name
     * @see java.io.File#getName()
     */
    public static String getFileName(String fileName) {
        File file = new File(fileName);
        return file.getName();
    }

    /**
     * ??????.
     * 
     * <pre>
     * {@code
     * Example 1: 
     * F:/pie2.png, return F:/pie2
     * 
     * Example 2: 
     * pie2.png, return pie2
     * }
     * </pre>
     * 
     * @param fileName
     *            ??
     * @return ??????
     * @see java.lang.String#substring(int, int)
     */
    public static String getFilePreName(String fileName) {
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    /**
     * ???(?. ?),?.
     * 
     * <p>
     * ???  "" (EMPTY)
     * </p>
     * 
     * <pre>
     * {@code
     * Example 1: 
     * F:/pie2.png, return png
     * 
     * Example 2: 
     * F:/pie2, return ""
     * }
     * </pre>
     * 
     * Gets the extension of a filename.
     * <p>
     * This method returns the textual part of the filename after the last dot. There must be no directory separator after the dot.
     * 
     * <pre>
     * foo.txt      --> "txt"
     * a/b/c.jpg    --> "jpg"
     * a/b.txt/c    --> ""
     * a/b/c        --> ""
     * </pre>
     * <p>
     * The output will be the same irrespective of the machine that the code is running on.
     * 
     * @param fileName
     *            ??
     * @return ?. ?
     * @see org.apache.commons.io.FilenameUtils#getExtension(String)
     * @see java.lang.String#substring(int, int)
     * @since 1.4.0
     */
    public static String getExtension(String fileName) {
        return StringUtils.defaultString(org.apache.commons.io.FilenameUtils.getExtension(fileName));
    }

    /**
     * ???,??.
     * 
     * <p>
     * ???  ""
     * </p>
     * 
     * @param fileName
     *            ??
     * @return ?. ?
     * @see org.apache.commons.io.FilenameUtils#getExtension(String)
     */
    public static String getFilePostfixNameLowerCase(String fileName) {
        return getExtension(fileName).toLowerCase();
    }

    // [start] ???

    /**
     * ?,??.
     * 
     * <p>
     * ?, .+newPostfixName
     * </p>
     * 
     * <pre>
     * {@code
     * Example 1:
     *      String fileName="F:/pie2.png";
     *       FileUtil.getNewFileName(fileName, "gif")
     *       
     *       return F:/pie2.gif
     * }
     * </pre>
     *
     * @param fileName
     *            ??, F:/pie2.png
     * @param newPostfixName
     *            ?.?,  gif
     * @return ??
     */
    public static String getNewFileName(String fileName, String newPostfixName) {
        if (Validator.isNullOrEmpty(fileName)) {
            throw new NullPointerException("fileName can't be null/empty!");
        }
        if (Validator.isNullOrEmpty(newPostfixName)) {
            throw new NullPointerException("newPostfixName can't be null/empty!");
        }

        // ?
        if (hasExtension(fileName)) {
            return fileName.substring(0, fileName.lastIndexOf(".") + 1) + newPostfixName;
        }
        // ?
        return fileName + "." + newPostfixName;
    }

    /**
     * ??.
     * 
     * @param fileName
     *            the file name
     * @return true, if successful
     * @see org.apache.commons.io.FilenameUtils#indexOfExtension(String)
     * @since 1.4.0
     */
    public static boolean hasExtension(String fileName) {
        return -1 != FilenameUtils.indexOfExtension(fileName);
    }

    // [end]

    /**
     *  ??.
     * 
     * <pre>
     * {@code
     *   Example 1:
     *      "mp2-product\\mp2-product-impl\\src\\main\\java\\com\\baozun\\mp2\\rpc\\impl\\item\\repo\\package-info.java"
     *      
     *       mp2-product
     * }
     * </pre>
     *
     * @param pathname
     *            ?????? File .,??.
     * @return ,, E:/  E:/
     * @since 1.0.7
     */
    public static String getFileTopParentName(String pathname) {
        if (Validator.isNullOrEmpty(pathname)) {
            throw new NullPointerException("pathname can't be null/empty!");
        }

        File file = new File(pathname);
        String parent = file.getParent();

        if (Validator.isNullOrEmpty(parent)) {
            return pathname;
        }

        //
        String fileTopParentName = getFileTopParentName(file);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("pathname:[{}],fileTopParentName:[{}]", pathname, fileTopParentName);
        }
        return fileTopParentName;
    }

    /**
     * ??.
     * 
     * <pre>
     * {@code
     *   Example 1:
     *      "mp2-product\\mp2-product-impl\\src\\main\\java\\com\\baozun\\mp2\\rpc\\impl\\item\\repo\\package-info.java"
     *      
     *       mp2-product
     * }
     * </pre>
     *
     * @param file
     *            the file
     * @return ,, E:/  E:/
     * @since 1.0.7
     */
    public static String getFileTopParentName(File file) {
        if (Validator.isNullOrEmpty(file)) {
            throw new NullPointerException("file can't be null/empty!");
        }

        File parent = file.getParentFile();
        if (Validator.isNullOrEmpty(parent)) {
            String name = file.getPath();//E:/--->E:\

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("parent is isNullOrEmpty,return file name:{}", name);
            }
            return name;
        }
        //
        String fileTopParentName = getFileTopParentName(parent);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("file.getAbsolutePath():[{}],fileTopParentName:[{}]", file.getAbsolutePath(),
                    fileTopParentName);
        }
        return fileTopParentName;
    }
}