com.feilong.commons.core.io.FileUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.feilong.commons.core.io.FileUtil.java

Source

/*
 * Copyright (C) 2008 feilong (venusdrogon@163.com)
 *
 * 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.feilong.commons.core.io;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feilong.commons.core.util.ArrayUtil;
import com.feilong.commons.core.util.Validator;

/**
 * {@link File}?<br>
 * 
 * File:
 * <ul>
 * <li>{@link File#getAbsolutePath()} </li>
 * <li>{@link File#getPath()} file</li>
 * <li>{@link File#getCanonicalPath()} ?CanonicalPath?...???.</li>
 * </ul>
 * 
 * @author <a href="mailto:venusdrogon@163.com"></a>
 * @version 1.0 2012-5-23 ?5:00:54
 * @version 1.0.7 2014-5-23 20:27 add {@link #getFileFormatSize(File)}
 * @see java.io.File
 * @since 1.0.0
 */
public final class FileUtil {

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

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

    /**
     * ?ByteArray.
     *
     * @param file
     *            file
     * @return byteArrayOutputStream.toByteArray();
     * @throws UncheckedIOException
     *             the unchecked io exception
     */
    public static final byte[] convertFileToByteArray(File file) throws UncheckedIOException {
        InputStream inputStream = FileUtil.getFileInputStream(file);

        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        byte[] bytes = new byte[IOConstants.DEFAULT_BUFFER_LENGTH];
        int j;

        try {
            while ((j = bufferedInputStream.read(bytes)) != -1) {
                byteArrayOutputStream.write(bytes, 0, j);
            }
            byteArrayOutputStream.flush();

            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } finally {
            try {
                // ???StreamClose.??Close
                // finally Block??close()
                byteArrayOutputStream.close();
                bufferedInputStream.close();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    }

    //*******************************************************************************

    /**
     * FileOutputStream? FileOutputStream <br>
     * FileOutputStream ???.?? FileWriter..
     *
     * @param fileName
     *            ??
     * @return FileOutputStream
     * @throws UncheckedIOException
     *             the unchecked io exception
     */
    public static final FileOutputStream getFileOutputStream(String fileName) throws UncheckedIOException {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
            return fileOutputStream;
        } catch (FileNotFoundException e) {
            throw new UncheckedIOException(e);
        }
    }

    /**
     * FileInputStream ?.??.<br>
     * FileInputStream ????.??? FileReader..
     *
     * @param fileName
     *            ?? fileName .
     * @return FileInputStream
     * @throws UncheckedIOException
     *             the unchecked io exception
     */
    public static final FileInputStream getFileInputStream(String fileName) throws UncheckedIOException {
        File file = new File(fileName);
        return getFileInputStream(file);
    }

    /**
     * FileInputStream ?.??.<br>
     * FileInputStream ????.??? FileReader..
     *
     * @param file
     *            ?.
     * @return FileInputStream
     * @throws UncheckedIOException
     *             the unchecked io exception
     */
    public static final FileInputStream getFileInputStream(File file) throws UncheckedIOException {
        try {
            // ???? FileNotFoundException.
            FileInputStream fileInputStream = new FileInputStream(file);
            return fileInputStream;
        } catch (FileNotFoundException e) {
            throw new UncheckedIOException(e);
        }
    }

    /**
     *  ?(?).
     * 
     * @param directory
     *            
     * @return <ul>
     *         <li>directory isNullOrEmpty,throw IllegalArgumentException</li>
     *         <li>directory don't exists,throw IllegalArgumentException</li>
     *         <li>directory is not Directory,throw IllegalArgumentException</li>
     *         <li>return file.list() ==0</li>
     *         </ul>
     */
    public static boolean isEmptyDirectory(String directory) {
        if (Validator.isNullOrEmpty(directory)) {
            throw new IllegalArgumentException("directory param " + directory + " can't be null/empty!");
        }
        File file = new File(directory);
        if (!file.exists()) {
            throw new IllegalArgumentException("directory file " + directory + " don't exists!");
        }

        if (!file.isDirectory()) {
            throw new IllegalArgumentException("directory file " + directory + " is not Directory!");
        }

        // Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
        // ??? null

        // ubuntu ? ok
        String[] list = file.list();

        int length = list.length;

        if (log.isDebugEnabled()) {

            log.debug("file :[{}] list length:[{}]", directory, length);

            for (String fileName : list) {
                log.debug(fileName);
            }
        }

        boolean flag = (length == 0);
        return flag;
    }

    // [start] ?(createDirectory/deleteFileOrDirectory/deleteFileOrDirectory)

    /**
     * <br>
     * ??.
     * 
     * @param folderPath
     *            , ??
     * @return  false,<br>
     *         ?true,<br>
     *         ?true
     */
    public static boolean createDirectory(String folderPath) {
        // ???
        File folder = new File(folderPath);
        if (!folder.exists()) {
            // mkdir  parent ? false ?
            boolean flag = folder.mkdirs();
            if (!flag) {
                log.warn("folder:[{}] make [faild]", folder);
            }
            return flag;
        } else {
            log.debug("the folder:[{}] exists,don't need mkdirs", folder);
        }
        return true;
    }

    /**
     * ?.
     * 
     * @param fileName
     *            ??
     */
    public static void deleteFileOrDirectory(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            deleteFileOrDirectory(file);
        } else {
            log.error(fileName + "?");
        }
    }

    /**
     * , , .
     * 
     * @param file
     *            ??
     */
    public static void deleteFileOrDirectory(File file) {
        if (file.exists() && file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files && files.length > 0) {
                for (File currentFile : files) {
                    if (!currentFile.isDirectory()) {
                        currentFile.delete();
                    } else {
                        deleteFileOrDirectory(currentFile);
                    }
                }
            }
            file.delete();
        } else {
            file.delete();
        }
    }

    // [end]

    // ************************************************************

    // [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 ??
     * @throws NullPointerException
     *             isNullOrEmpty(fileName) or isNullOrEmpty(newPostfixName)
     */
    public static final String getNewFileName(String fileName, String newPostfixName) throws NullPointerException {

        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 (hasPostfixName(fileName)) {
            return fileName.substring(0, fileName.lastIndexOf(".") + 1) + newPostfixName;
        }
        // ?
        return fileName + "." + newPostfixName;
    }

    /**
     * ??.
     * 
     * @param fileName
     *            the file name
     * @return true, if successful
     */
    public static final boolean hasPostfixName(String fileName) {
        String fileNameString = getFileName(fileName);
        int lastIndexOf = fileNameString.lastIndexOf(".");
        if (-1 == lastIndexOf) {
            return false;
        }
        return true;
    }

    /**
     * ???(?. ?),?<br>
     * ???  "" (EMPTY).
     * 
     * <pre>
     * {@code
     * Example 1: 
     * F:/pie2.png, return png
     * 
     * Example 2: 
     * F:/pie2, return ""
     * }
     * </pre>
     * 
     * @param fileName
     *            ??
     * @return ?. ?
     * @see org.apache.commons.io.FilenameUtils#getExtension(String)
     * @see java.lang.String#substring(int, int)
     */
    public static final String getFilePostfixName(String fileName) {
        if (hasPostfixName(fileName)) {
            String filePostfixName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            return filePostfixName;
        }
        return "";
    }

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

    /**
     * ??????. <br>
     * 
     * <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 final String getFilePreName(String fileName) {
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

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

    // [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:/
     * @throws NullPointerException
     *             isNullOrEmpty(fileName)
     * 
     * @since 1.0.7
     */
    public static final String getFileTopParentName(String pathname) throws NullPointerException {
        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 (log.isDebugEnabled()) {
            log.debug("pathname:[{}],fileTopParentName:[{}]", pathname, fileTopParentName);
        }
        return fileTopParentName;
    }

    /**
     *  parent.
     *
     * @param pathname
     *            the pathname
     * @return the parent
     * @throws NullPointerException
     *             the null pointer exception
     */
    public static String getParent(String pathname) throws NullPointerException {
        if (Validator.isNullOrEmpty(pathname)) {
            throw new NullPointerException("pathname can't be null/empty!");
        }
        File file = new File(pathname);
        String parent = file.getParent();
        return parent;
    }

    /**
     *  ??
     * 
     * <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:/
     * @throws NullPointerException
     *             isNullOrEmpty(fileName)
     * @since 1.0.7
     */
    public static final String getFileTopParentName(File file) throws NullPointerException {
        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 (log.isDebugEnabled()) {
                log.debug("parent is isNullOrEmpty,return file name:{}", name);
            }
            return name;
        }
        //
        String fileTopParentName = getFileTopParentName(parent);

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

    /**
     * ?.
     * 
     * @param filePath
     *            the file path
     * @return ,true
     */
    public static final boolean isExistFile(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * ?.
     * 
     * @param filePath
     *            the file path
     * @return ?,true
     * @since 1.0.3
     */
    public static final boolean isNotExistFile(String filePath) {
        return !isExistFile(filePath);
    }

    // ************************************************************************
    //
    // ??
    //
    // ************************************************************************
    /**
     * ??.
     * 
     * @param fileName
     *            ??,? ,? ,?????
     * @return ??
     */
    public static final boolean isCommonImage(String fileName) {
        return isInAppointTypes(fileName, IOConstants.COMMON_IMAGES);
    }

    /**
     * ??.
     * 
     * @param fileName
     *            ??
     * @param appointTypes
     *            
     * @return ??
     */
    // XXX ?
    public static final boolean isInAppointTypes(String fileName, String[] appointTypes) {
        return ArrayUtil.isContain(appointTypes, getFilePostfixName(fileName));
    }

    // ************************************************************
    /**
     * ??.
     * <p>
     * ???? GB MB KB???? Bytes
     * </p>
     * <p>
     * Common-io 2.4{@link org.apache.commons.io.FileUtils#byteCountToDisplaySize(long)}GB ??1.99G 1Gapache ?
     * </p>
     * 
     * @param fileSize
     *            ? ??byte
     * @return ?byte ?
     * @see #getFileSize(File)
     * @see IOConstants#GB
     * @see IOConstants#MB
     * @see IOConstants#KB
     * 
     * @see org.apache.commons.io.FileUtils#byteCountToDisplaySize(long)
     */
    public static final String formatSize(long fileSize) {
        String danwei = "Bytes";
        // ?
        String yushu = "";
        // 
        long chushu = 1;
        if (fileSize >= IOConstants.GB) {
            danwei = "GB";
            chushu = IOConstants.GB;
        } else if (fileSize >= IOConstants.MB) {
            danwei = "MB";
            chushu = IOConstants.MB;
        } else if (fileSize >= IOConstants.KB) {
            danwei = "KB";
            chushu = IOConstants.KB;
        }
        if (chushu == 1) {
            return fileSize + danwei;
        }
        yushu = 100 * (fileSize % chushu) / chushu + "";
        if ("0".equals(yushu)) {
            return fileSize / chushu + danwei;
        }
        return fileSize / chushu + "." + yushu + danwei;
    }

    /**
     * ??.
     * 
     * <p>
     * 3834,?? 3.74KB<br>
     * 36830335 , ??:35.12MB<br>
     * 2613122669 , ?? : 2.43GB<br>
     * </p>
     * 
     * <p>
     * ???? GB MB KB???? Bytes
     * </p>
     *
     * @param file
     *            the file
     * @return the file format size
     * @throws NullPointerException
     *             isNullOrEmpty(file)
     * @see #getFileSize(File)
     * @see IOConstants#GB
     * @see IOConstants#MB
     * @see IOConstants#KB
     * @see org.apache.commons.io.FileUtils#byteCountToDisplaySize(long)
     * @since 1.0.7
     */
    public static final String getFileFormatSize(File file) throws NullPointerException {
        if (Validator.isNullOrEmpty(file)) {
            throw new NullPointerException("file can't be null/empty!");
        }
        long fileSize = getFileSize(file);
        return formatSize(fileSize);
    }

    /**
     * ??(??).
     * 
     * @param file
     *            
     * @return ????<br>
     *         ? 0L.<br>
     *         ?????? 0L.
     * @see File#length()
     */
    public static long getFileSize(File file) {
        return file.length();
    }

    /**
     * ?file.
     *
     * @param filePath
     *            file
     * @return the file
     * @throws IllegalArgumentException
     *             if Validator.isNullOrEmpty(filePath)
     * @see #getFormatFileName(String)
     * @since 1.0.7
     */
    static final File cascadeMkdirs(final String filePath) throws IllegalArgumentException {
        if (Validator.isNullOrEmpty(filePath)) {
            throw new IllegalArgumentException("filePath can't be null/empty!");
        }

        File file = new File(filePath);

        if (file.exists()) {
            // 
            if (file.isDirectory()) {
                log.error("File '" + file + "' exists but is a directory");
                throw new IllegalArgumentException("File '" + file + "' exists but is a directory");
            }
            // ?
            else if (!file.canWrite()) {
                log.error("File '" + file + "' cannot be written to");
                throw new IllegalArgumentException("File '" + file + "' cannot be written to");
            }
        }
        // ?
        else {
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                boolean flag = parent.mkdirs();
                // ? 
                if (!flag) {
                    log.error("File '" + file + "' could not be created");
                    throw new IllegalArgumentException("File '" + file + "' could not be created");
                }
            }
        }
        return file;
    }

    /**
     * ??? ???,???.
     * 
     * @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)) {
                log.warn("formatFileName:[{}] contains oldChar:[{}],will replace newChar:[{}]", formatFileName,
                        oldChar, newChar);
                formatFileName = formatFileName.replace(oldChar, newChar);
            }
        }
        return formatFileName;
    }

    /**
     * ??????????? .
     * <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 = { //
            //         { "\\", "" }, // \
            //   { "/", "" }, // /
            { "\"", "" }, // "
            { ":", "" }, // :
            { "*", "" }, // *
            { "?", "" }, // ?
            { "<", "" }, // <
            { ">", "" }, // >
            { "|", "" }, // |
    };
}