com.fjn.helper.common.io.file.common.FileUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.fjn.helper.common.io.file.common.FileUtil.java

Source

/*
 *
 *  Copyright 2018 FJN Corp.
 *
 *  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.
 *
 *  Author                        Date                       Issue
 *  fs1194361820@163.com          2015-01-01                 Initial Version
 *
 */

package com.fjn.helper.common.io.file.common;

import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fjn.helper.common.exception.FileDirFaultException;
import com.fjn.helper.common.util.EncodingUtil;
import com.fjn.helper.common.util.StringUtil;

/**
 * ??
 * filename=name.suffix; name???prefix
 * @author fs1194361820@163.com
 *
 */
public class FileUtil extends FileUtils {
    //   private static final Logger logger=Logger.getLogger(FileHelper.class);
    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
    private static final String SPARTATOR_WINDOWS = "\\"; // Windows
    private static final String SPARTATOR_UNIX = "/"; // UNIX
    private static FileNameMap filenamemap = new FileNameMapImpl();

    /**
     * ?????\/:*?">|<
     * \\\\ \
     * /   /
     * :   :
     * \\*   *
     * \\?   ?
     * \"   "
     * >   >
     * <   <
     * \\|   |
     *
     * 
     * @param filename
     * @return true ???false??
     */
    public static boolean checkFileName(String filename) {
        boolean noExist = true; // noExist:?
        noExist = filename.matches("^[^\\\\/:\\*\\?\">\\|<]+(\\.[^\\\\/:\\*\\?\">\\|<]+)?$");
        return noExist;
    }

    /**
     * ????
     * /usr/hello/hell.xml??? {UNIX }
     * c:\windows\system2\hell.xml???{Windows }
     * @param filepath
     */
    public static String getRealFileName(String filepath) {
        if (StringUtil.isNull(filepath)) {
            log.error("Parameter 'filepath' is Null !", new IllegalArgumentException());
        }
        int unixLastIndex = filepath.lastIndexOf("/");
        int winLasIndex = filepath.lastIndexOf("\\");
        int index = -1;
        if (unixLastIndex > winLasIndex)
            index = unixLastIndex;
        if (unixLastIndex < winLasIndex)
            index = winLasIndex;

        if (index == -1) {
            return filepath;
        }
        return filepath.substring(index + 1);
    }

    /**
     * ??????
     * 
     * @param filePath
     * @return
     */
    public static String getFilePrefix(String filePath) {
        String filename = getRealFileName(filePath);
        int index = filename.indexOf(".");
        if (index != -1)
            return filename.substring(0, index);
        return filename;
    }

    /**
     * ???
     * @param filename
     * @return
     */
    public static String getFileSuffix(String filename) {
        if (StringUtil.isNull(filename)) {
            log.error("Parameter 'filename' is Null !", new IllegalArgumentException());
        }
        int index = filename.lastIndexOf(".");
        if (index == -1 || index == filename.length() - 1) {
            log.error("Parameter 'filename' is not a file name !",
                    new IllegalArgumentException("Parameter [ filename ] is not a file name ."));
        }
        return filename.substring(index + 1);
    }

    /**
     * ???
     * @return
     */
    public static String suffixToLowCase(String filename) {
        String suffix = getFileSuffix(filename);
        return getFilePrefix(filename) + "." + suffix.toLowerCase();
    }

    /**
     * ??
     * @param filename
     * @param fileSuffix
     * @return
     */
    public static String setFileSuffix(String filename, String fileSuffix) {
        return getFilePrefix(filename) + "." + fileSuffix;
    }

    /**
     * ?????
     * @param filename
     * @return
     */
    public static String getFileNameForDownload(String filename) {
        return EncodingUtil.encodeFileName(filename);
    }

    public static File ensureFileExists(File file) {
        try {
            if (!file.exists()) {
                if (!file.createNewFile()) {
                    throw new FileDirFaultException(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * ?filename??
     * @param dir 
     * @param filename
     * @return
     */
    public static File ensureFileExists(String dirPath, String filename) {
        // ??
        File dir = ensureDirExists(dirPath);
        File file = new File(dir, filename);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return file;
    }

    /**
     * ?filename??
     * @param dir
     * @param filename
     * @return
     */
    public static File ensureFileExists(File dir, String filename) {
        // ??
        dir = ensureDirExists(dir);
        File file = new File(dir, filename);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return file;
    }

    /**
     * ?
     * c:\hello\zhang\heel.xml
     * @param filepath
     * @return
     */
    public static String getParentDirPath(String filepath) {
        if (StringUtil.isNull(filepath)) {
            log.error("Parameter 'filepath' is Null !", new IllegalArgumentException());
        }
        int unixLastIndex = filepath.lastIndexOf("/");
        int winLasIndex = filepath.lastIndexOf("\\");
        int index = -1;
        if (unixLastIndex > winLasIndex)
            index = unixLastIndex;
        if (unixLastIndex < winLasIndex)
            index = winLasIndex;

        if (index == -1) {
            return "";
        }
        return filepath.substring(0, index);
    }

    /**
     * ?
     * @param dir
     * @return
     */
    public static File ensureDirExists(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new FileDirFaultException(dir);
            }
        }
        return file;
    }

    /**
     * ?
     * @param dir
     * @return
     */
    public static File ensureDirExists(File dir) {
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                throw new FileDirFaultException(dir.getPath());
            }
        }
        return dir;
    }

    public static File ensureChildDirExists(String parentDir, String childDir) {
        File parent = ensureDirExists(parentDir);
        String child = parent.getPath() + File.separator + childDir;
        File file = ensureDirExists(child);
        return file;
    }

    /**
     * ?parentDir?childDir
     * @param parentDir
     * @param childDir
     * @return
     */
    public static File ensureChildDirExists(File parentDir, String childDir) {
        parentDir = ensureDirExists(parentDir);
        String child = parentDir.getPath() + File.separator + childDir;
        File file = ensureDirExists(child);
        return file;
    }

    /**
     *  ?
     * @param filepath
     * @return
     */
    public static String removeFirstIfIsSparator(String filepath) {
        if (StringUtil.isNull(filepath))
            return "";

        if (filepath.startsWith(SPARTATOR_UNIX) || filepath.startsWith(SPARTATOR_WINDOWS)) {
            return removeFirstIfIsSparator(filepath.substring(1));
        }
        return filepath;
    }

    public static void main(String[] args) {
        log.info(getRealFileName("hell.xml"));
        log.info(getRealFileName("/usr/hello/hell.xml"));
        log.info(getRealFileName("c:\\windows\\system2\\hell.xml"));
        log.info(getRealFileName("c:\\windows\\system2/.xml"));

        log.info(getFilePrefix("hell.xml"));
        log.info(getFilePrefix("/usr/hello/hell.xml"));
        log.info(getFilePrefix("c:\\windows\\system2\\hell.xml"));
        log.info(getFilePrefix("c:\\windows\\system2/.xml"));

        log.info(removeFirstIfIsSparator("////usr/hello/hell.xml"));
        log.info(removeFirstIfIsSparator("\\\\usr/hello/hell.xml"));
        log.info(removeFirstIfIsSparator("/usr/hello/hell.xml"));
    }

    public static String getMimeType(String filename) {
        return filenamemap.getContentTypeFor(suffixToLowCase(filename));
    }

}