com.fengduo.spark.commons.file.FileUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.fengduo.spark.commons.file.FileUtils.java

Source

/*
 * Copyright 2015-2020 MSUN.com All right reserved. This software is the confidential and proprietary information of
 * MSUN.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with MSUN.com.
 */
package com.fengduo.spark.commons.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fengduo.spark.commons.util.StringUtils;

/**
 * ?
 * 
 * <pre>
 *  ????????????
 * </pre>
 * 
 * @author zxc Jun 4, 2015 12:46:39 PM
 */
public class FileUtils extends org.apache.commons.io.FileUtils {

    private static Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**
     * ??
     */
    public static long ONE_KB = 1024;
    public static long ONE_MB = ONE_KB * 1024;
    public static long ONE_GB = ONE_MB * 1024;
    public static long ONE_TB = ONE_GB * (long) 1024;
    public static long ONE_PB = ONE_TB * (long) 1024;

    public static String getHumanReadableFileSize(Long fileSize) {
        if (fileSize == null)
            return null;
        return getHumanReadableFileSize(fileSize.longValue());
    }

    public static String getHumanReadableFileSize(long fileSize) {
        if (fileSize < 0) {
            return String.valueOf(fileSize);
        }
        String result = getHumanReadableFileSize(fileSize, ONE_PB, "PB");
        if (result != null) {
            return result;
        }

        result = getHumanReadableFileSize(fileSize, ONE_TB, "TB");
        if (result != null) {
            return result;
        }
        result = getHumanReadableFileSize(fileSize, ONE_GB, "GB");
        if (result != null) {
            return result;
        }
        result = getHumanReadableFileSize(fileSize, ONE_MB, "MB");
        if (result != null) {
            return result;
        }
        result = getHumanReadableFileSize(fileSize, ONE_KB, "KB");
        if (result != null) {
            return result;
        }
        return String.valueOf(fileSize) + "B";
    }

    private static String getHumanReadableFileSize(long fileSize, long unit, String unitName) {
        if (fileSize == 0)
            return "0";

        if (fileSize / unit >= 1) {
            double value = fileSize / (double) unit;
            DecimalFormat df = new DecimalFormat("######.##" + unitName);
            return df.format(value);
        }
        return null;
    }

    /**
     * ???
     * 
     * @param srcFileName ???
     * @param descFileName ??
     * @return ??true?false
     */
    public static boolean copyFile(String srcFileName, String descFileName) {
        return FileUtils.copyFileCover(srcFileName, descFileName, false);
    }

    /**
     * ??
     * 
     * @param srcFileName ???
     * @param descFileName ??
     * @param coverlay ?
     * @return ??true?false
     */
    public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) {
        File srcFile = new File(srcFileName);
        // ??
        if (!srcFile.exists()) {
            log.debug("?? " + srcFileName + " ?!");
            return false;
        }
        // ???
        else if (!srcFile.isFile()) {
            log.debug("?" + srcFileName + " ?!");
            return false;
        }
        File descFile = new File(descFileName);
        // ?
        if (descFile.exists()) {
            // ?
            if (coverlay) {
                log.debug("!");
                if (!FileUtils.delFile(descFileName)) {
                    log.debug(" " + descFileName + " !");
                    return false;
                }
            } else {
                log.debug("? " + descFileName + " !");
                return false;
            }
        } else {
            if (!descFile.getParentFile().exists()) {
                // ?
                log.debug("?!");
                // 
                if (!descFile.getParentFile().mkdirs()) {
                    log.debug("!");
                    return false;
                }
            }
        }

        // ?
        // ??
        int readByte = 0;
        InputStream ins = null;
        OutputStream outs = null;
        try {
            // ?
            ins = new FileInputStream(srcFile);
            // ?
            outs = new FileOutputStream(descFile);
            byte[] buf = new byte[1024];
            // ?1024readByte-1??
            while ((readByte = ins.read(buf)) != -1) {
                // ???
                outs.write(buf, 0, readByte);
            }
            log.debug("?? " + srcFileName + " " + descFileName + "?!");
            return true;
        } catch (Exception e) {
            log.debug("?" + e.getMessage());
            return false;
        } finally {
            // ?????
            if (outs != null) {
                try {
                    outs.close();
                } catch (IOException oute) {
                    oute.printStackTrace();
                }
            }
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException ine) {
                    ine.printStackTrace();
                }
            }
        }
    }

    /**
     * ??
     * 
     * @param srcDirName ???
     * @param descDirName ??
     * @return ??true?false
     */
    public static boolean copyDirectory(String srcDirName, String descDirName) {
        return FileUtils.copyDirectoryCover(srcDirName, descDirName, false);
    }

    /**
     * ?
     * 
     * @param srcDirName ???
     * @param descDirName ??
     * @param coverlay ?
     * @return ??true?false
     */
    public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) {
        File srcDir = new File(srcDirName);
        // ??
        if (!srcDir.exists()) {
            log.debug("?? " + srcDirName + " ?!");
            return false;
        }
        // ??
        else if (!srcDir.isDirectory()) {
            log.debug("?" + srcDirName + " ?!");
            return false;
        }
        // ???
        String descDirNames = descDirName;
        if (!descDirNames.endsWith(File.separator)) {
            descDirNames = descDirNames + File.separator;
        }
        File descDir = new File(descDirNames);
        // 
        if (descDir.exists()) {
            if (coverlay) {
                // ?
                log.debug("!");
                if (!FileUtils.delFile(descDirNames)) {
                    log.debug(" " + descDirNames + " !");
                    return false;
                }
            } else {
                log.debug("? " + descDirNames + " !");
                return false;
            }
        } else {
            // 
            log.debug("?!");
            if (!descDir.mkdirs()) {
                log.debug("!");
                return false;
            }

        }

        boolean flag = true;
        // ??????
        File[] files = srcDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            // ??
            if (files[i].isFile()) {
                flag = FileUtils.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName());
                // ?
                if (!flag) {
                    break;
                }
            }
            // ??
            if (files[i].isDirectory()) {
                flag = FileUtils.copyDirectory(files[i].getAbsolutePath(), descDirName + files[i].getName());
                // ?
                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            log.debug("? " + srcDirName + "  " + descDirName + " !");
            return false;
        }
        log.debug("? " + srcDirName + "  " + descDirName + " ?!");
        return true;

    }

    /**
     * ??
     * 
     * @param fileName ??
     * @return ?true?false
     */
    public static boolean delFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            log.debug(fileName + " ?!");
            return true;
        } else {
            if (file.isFile()) {
                return FileUtils.deleteFile(fileName);
            } else {
                return FileUtils.deleteDirectory(fileName);
            }
        }
    }

    /**
     * ?
     * 
     * @param fileName ??
     * @return ?true?false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                log.debug(" " + fileName + " ?!");
                return true;
            } else {
                log.debug(" " + fileName + " !");
                return false;
            }
        } else {
            log.debug(fileName + " ?!");
            return true;
        }
    }

    /**
     * ?
     * 
     * @param dirName 
     * @return ?true?false
     */
    public static boolean deleteDirectory(String dirName) {
        String dirNames = dirName;
        if (!dirNames.endsWith(File.separator)) {
            dirNames = dirNames + File.separator;
        }
        File dirFile = new File(dirNames);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            log.debug(dirNames + " ?!");
            return true;
        }
        boolean flag = true;
        // ??
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // ?
            if (files[i].isFile()) {
                flag = FileUtils.deleteFile(files[i].getAbsolutePath());
                // 
                if (!flag) {
                    break;
                }
            }
            // ?
            else if (files[i].isDirectory()) {
                flag = FileUtils.deleteDirectory(files[i].getAbsolutePath());
                // ?
                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            log.debug("!");
            return false;
        }
        // ?
        if (dirFile.delete()) {
            log.debug(" " + dirName + " ?!");
            return true;
        } else {
            log.debug(" " + dirName + " !");
            return false;
        }

    }

    /**
     * ?
     * 
     * @param descFileName ???
     * @return ?true?false
     */
    public static boolean createFile(String descFileName) {
        File file = new File(descFileName);
        if (file.exists()) {
            log.debug(" " + descFileName + " !");
            return false;
        }
        if (descFileName.endsWith(File.separator)) {
            log.debug(descFileName + " ?!");
            return false;
        }
        if (!file.getParentFile().exists()) {
            // ?
            if (!file.getParentFile().mkdirs()) {
                log.debug("!");
                return false;
            }
        }

        // 
        try {
            if (file.createNewFile()) {
                log.debug(descFileName + " ?!");
                return true;
            } else {
                log.debug(descFileName + " !");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug(descFileName + " !");
            return false;
        }

    }

    /**
     * 
     * 
     * @param descDirName ??,?
     * @return ?true?false
     */
    public static boolean createDirectory(String descDirName) {
        String descDirNames = descDirName;
        if (!descDirNames.endsWith(File.separator)) {
            descDirNames = descDirNames + File.separator;
        }
        File descDir = new File(descDirNames);
        if (descDir.exists()) {
            log.debug(" " + descDirNames + " !");
            return false;
        }
        // 
        if (descDir.mkdirs()) {
            log.debug(" " + descDirNames + " ?!");
            return true;
        } else {
            log.debug(" " + descDirNames + " !");
            return false;
        }

    }

    /**
     * 
     * 
     * @param file ?
     */
    public static void writeToFile(String fileName, String content, boolean append) {
        try {
            FileUtils.write(new File(fileName), content, "utf-8", append);
            log.debug(" " + fileName + " ?!");
        } catch (IOException e) {
            log.debug(" " + fileName + " ! " + e.getMessage());
        }
    }

    /**
     * 
     * 
     * @param file ?
     */
    public static void writeToFile(String fileName, String content, String encoding, boolean append) {
        try {
            FileUtils.write(new File(fileName), content, encoding, append);
            log.debug(" " + fileName + " ?!");
        } catch (IOException e) {
            log.debug(" " + fileName + " ! " + e.getMessage());
        }
    }

    /**
     * 
     * 
     * @param srcDirName 
     * @param fileName ????*""
     * @param descFileName zip
     */
    public static void zipFiles(String srcDirName, String fileName, String descFileName) {
        // ?
        if (srcDirName == null) {
            log.debug(" " + srcDirName + " ?!");
            return;
        }
        File fileDir = new File(srcDirName);
        if (!fileDir.exists() || !fileDir.isDirectory()) {
            log.debug(" " + srcDirName + " ?!");
            return;
        }
        String dirPath = fileDir.getAbsolutePath();
        File descFile = new File(descFileName);
        try {
            ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile));
            if ("*".equals(fileName) || "".equals(fileName)) {
                FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts);
            } else {
                File file = new File(fileDir, fileName);
                if (file.isFile()) {
                    FileUtils.zipFilesToZipFile(dirPath, file, zouts);
                } else {
                    FileUtils.zipDirectoryToZipFile(dirPath, file, zouts);
                }
            }
            zouts.close();
            log.debug(descFileName + " ?!");
        } catch (Exception e) {
            log.debug("" + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * ZIPZIPdescFileName
     * 
     * @param zipFileName ?ZIP
     * @param descFileName 
     */
    public static boolean unZipFiles(String zipFileName, String descFileName) {
        String descFileNames = descFileName;
        if (!descFileNames.endsWith(File.separator)) {
            descFileNames = descFileNames + File.separator;
        }
        try {
            // ?ZIPZipFile
            ZipFile zipFile = new ZipFile(zipFileName);
            ZipEntry entry = null;
            String entryName = null;
            String descFileDir = null;
            byte[] buf = new byte[4096];
            int readByte = 0;
            // ?ZIPentry
            @SuppressWarnings("rawtypes")
            Enumeration enums = zipFile.getEntries();
            // ??entry
            while (enums.hasMoreElements()) {
                entry = (ZipEntry) enums.nextElement();
                // entry??
                entryName = entry.getName();
                descFileDir = descFileNames + entryName;
                if (entry.isDirectory()) {
                    // entry
                    new File(descFileDir).mkdirs();
                    continue;
                } else {
                    // entry
                    new File(descFileDir).getParentFile().mkdirs();
                }
                File file = new File(descFileDir);
                // ?
                OutputStream os = new FileOutputStream(file);
                // ZipFileentry?
                InputStream is = zipFile.getInputStream(entry);
                while ((readByte = is.read(buf)) != -1) {
                    os.write(buf, 0, readByte);
                }
                os.close();
                is.close();
            }
            zipFile.close();
            log.debug("?!");
            return true;
        } catch (Exception e) {
            log.debug("" + e.getMessage());
            return false;
        }
    }

    /**
     * ZIP?
     * 
     * @param dirPath 
     * @param fileDir ?
     * @param zouts ?
     */
    public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {
        if (fileDir.isDirectory()) {
            File[] files = fileDir.listFiles();
            // 
            if (files.length == 0) {
                // ?
                ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
                try {
                    zouts.putNextEntry(entry);
                    zouts.closeEntry();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }

            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    // 
                    FileUtils.zipFilesToZipFile(dirPath, files[i], zouts);
                } else {
                    // 
                    FileUtils.zipDirectoryToZipFile(dirPath, files[i], zouts);
                }
            }

        }

    }

    /**
     * ZIP?
     * 
     * @param dirPath 
     * @param file 
     * @param zouts ?
     */
    public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
        FileInputStream fin = null;
        ZipEntry entry = null;
        // ?
        byte[] buf = new byte[4096];
        int readByte = 0;
        if (file.isFile()) {
            try {
                // ?
                fin = new FileInputStream(file);
                // ZipEntry
                entry = new ZipEntry(getEntryName(dirPath, file));
                // ?
                zouts.putNextEntry(entry);
                // ?
                while ((readByte = fin.read(buf)) != -1) {
                    zouts.write(buf, 0, readByte);
                }
                zouts.closeEntry();
                fin.close();
                System.out.println(" " + file.getAbsolutePath() + " zip!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * ?ZIPentry?????
     * 
     * @param dirPat ??
     * @param file entry??
     * @return
     */
    private static String getEntryName(String dirPath, File file) {
        String dirPaths = dirPath;
        if (!dirPaths.endsWith(File.separator)) {
            dirPaths = dirPaths + File.separator;
        }
        String filePath = file.getAbsolutePath();
        // entry????"/"
        if (file.isDirectory()) {
            filePath += "/";
        }
        int index = filePath.indexOf(dirPaths);

        return filePath.substring(index + dirPaths.length());
    }

    /**
     * ? \\  / ? File.separator
     * 
     * @param path
     * @return
     */
    public static String path(String path) {
        String p = StringUtils.replace(path, "\\", "/");
        p = StringUtils.join(StringUtils.split(p, "/"), "/");
        if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")) {
            p += "/";
        }
        if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")) {
            p = p + "/";
        }
        return p;
    }
}