com.ieasy.basic.util.file.FileUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.ieasy.basic.util.file.FileUtils.java

Source

/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.ieasy.basic.util.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.text.DecimalFormat;

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

import com.alibaba.fastjson.JSON;

/**
 * ? ??????????
 * 
 * @author ThinkGem
 * @version 2013-06-21
 */
public class FileUtils extends org.apache.commons.io.FileUtils {

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

    /**
     * ???
     * 
     * @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()) {
            logger.debug("?? " + srcFileName + " ?!");
            return false;
        }
        // ???
        else if (!srcFile.isFile()) {
            logger.debug("?" + srcFileName + " ?!");
            return false;
        }
        File descFile = new File(descFileName);
        // ?
        if (descFile.exists()) {
            // ?
            if (coverlay) {
                logger.debug("!");
                if (!FileUtils.delFile(descFileName)) {
                    logger.debug(" " + descFileName + " !");
                    return false;
                }
            } else {
                logger.debug("? " + descFileName + " !");
                return false;
            }
        } else {
            if (!descFile.getParentFile().exists()) {
                // ?
                logger.debug("?!");
                // 
                if (!descFile.getParentFile().mkdirs()) {
                    logger.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);
            }
            logger.debug("?? " + srcFileName + " " + descFileName + "?!");
            return true;
        } catch (Exception e) {
            logger.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()) {
            logger.debug("?? " + srcDirName + " ?!");
            return false;
        }
        // ??
        else if (!srcDir.isDirectory()) {
            logger.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) {
                // ?
                logger.debug("!");
                if (!FileUtils.delFile(descDirNames)) {
                    logger.debug(" " + descDirNames + " !");
                    return false;
                }
            } else {
                logger.debug("? " + descDirNames + " !");
                return false;
            }
        } else {
            // 
            logger.debug("?!");
            if (!descDir.mkdirs()) {
                logger.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) {
            logger.debug("? " + srcDirName + "  " + descDirName + " !");
            return false;
        }
        logger.debug("? " + srcDirName + "  " + descDirName + " ?!");
        return true;

    }

    /**
     * ??
     * @param fileName ??
     * @return ?true?false
     */
    public static boolean delFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            logger.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(File file) {
        if (null == file) {
            logger.error("Filenull");
            return false;
        }

        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                logger.debug("? ?[" + file + "]");
                return true;
            } else {
                logger.error("?[" + file + "]");
                return false;
            }
        } else {
            logger.error("??[" + file + "]");
            return true;
        }
    }

    /**
     * ?
     * @param fileName ??
     * @return ?true?false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                logger.debug("? ?[" + fileName + "]");
                return true;
            } else {
                logger.error("?[" + fileName + "]");
                return false;
            }
        } else {
            logger.error("??[" + 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()) {
            logger.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) {
            logger.debug("!");
            return false;
        }
        // ?
        if (dirFile.delete()) {
            logger.debug("?[" + dirName + "]");
            return true;
        } else {
            logger.debug("[" + dirName + "]");
            return false;
        }

    }

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

        // 
        try {
            if (file.createNewFile()) {
                logger.debug(descFileName + " ?!");
                return true;
            } else {
                logger.debug(descFileName + " !");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.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()) {
            logger.debug(" " + descDirNames + " !");
            return false;
        }
        // 
        if (descDir.mkdirs()) {
            logger.debug(" " + descDirNames + " ?!");
            return true;
        } else {
            logger.debug(" " + descDirNames + " !");
            return false;
        }
    }

    /**
     * 
     * 
     * @param content
     * @param filePath
     */
    public static void writeFile(String content, String filePath) {
        try {
            if (FileUtils.createFile(filePath)) {
                FileWriter fileWriter = new FileWriter(filePath, true);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                bufferedWriter.write(content);
                bufferedWriter.close();
                fileWriter.close();
            } else {
                logger.debug("??");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ??? <b>function:</b> type??????type
     * <p>
     * example: type = html index.html.html -> index.html
     * </p>
     * <p>
     * example: type = zh_CN index.html.zh_CN -> index.html
     * </p>
     * <p>
     * batchRename("F:\\server\\chat-tomcat-7.0.32\\webapps\\jwchat", "zh_CN");
     * </p>
     * 
     * @author hoojo
     * @createDate 2012-5-16 ?02:16:48
     * @param path
     * @param type
     * @throws Exception
     */
    public static void batchRename(String path, String type) throws Exception {
        if (path == null || "".equals(path)) {
            throw new Exception("???");
        }
        File dir = new File(path);
        File[] list = dir.listFiles();
        for (File file : list) {
            String name = file.getName();
            String[] s = name.split("\\.");
            if (s.length == 3 && type.equals(s[2])) {
                System.out.println(s[0] + "--" + s[1] + "--" + s[2]);
                file.renameTo(new File(path + "/" + s[0] + "." + s[1]));
            }
        }
    }

    public static void WriteJSON(String outPath, Object obj) {
        WriteJSON(outPath, null, obj);
    }

    public static void WriteJSON(String outPath, String perfix, Object obj) {
        try {
            String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss");
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outPath), "UTF-8");
            out.write((null != perfix ? perfix : "") + json);
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error("?JSON" + e.getMessage());
        }
        logger.debug("?JSON-->" + outPath);
    }

    /**
     * ??????
     * 
     * @param fileName
     *            ??
     */
    public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("???");
            // 
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        try {
            System.out.println("???");
            // 
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            in = new FileInputStream(fileName);
            showAvailableBytes(in);
            // byteread
            while ((byteread = in.read(tempbytes)) != -1) {
                System.out.write(tempbytes, 0, byteread);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * ???
     * 
     * @param fileName
     *            ??
     */
    public static void readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("???");
            // 
            reader = new InputStreamReader(new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                // windowsrn?
                // ?
                // ?r?n?
                if (((char) tempchar) != 'r') {
                    System.out.print((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println("???");
            // 
            char[] tempchars = new char[30];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileName));
            // charread?
            while ((charread = reader.read(tempchars)) != -1) {
                // ??r?
                if ((charread == tempchars.length) && (tempchars[tempchars.length - 1] != 'r')) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == 'r') {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * ??????
     * 
     * @param fileName
     *            ??
     */
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("???");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // null?
            while ((tempString = reader.readLine()) != null) {
                // ?
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * ??
     * 
     * @param fileName
     *            ??
     */
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("??");
            // ????
            randomFile = new RandomAccessFile(fileName, "r");
            // 
            long fileLength = randomFile.length();
            // ?
            int beginIndex = (fileLength > 4) ? 4 : 0;
            // ?beginIndex?
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
            // 10?10
            // ?byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                System.out.write(bytes, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * ?
     * 
     * @param in
     */
    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("??:" + in.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * ??
     * 
     * @param filePath
     *            ??
     * @param definedName
     *            ??
     * @return
     */
    public static boolean rename(String filePath, String definedName) {
        File file = new File(filePath);
        if (file.exists()) {
            String fileExt = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();

            String rename = file.getParent() + "/" + definedName + "." + fileExt;

            if (file.renameTo(new File(rename))) {
                logger.debug("???{} TO {}", file.getAbsoluteFile(), rename);
                return true;
            } else {
                logger.debug("??{} TO {}", file.getAbsoluteFile(),
                        rename);
                return false;
            }
        } else {
            logger.debug("?{}", file.getAbsoluteFile());
            return false;
        }
    }

    /**
     * ???
     * 
     * @param filename
     * @return
     */
    public static String getExtend(String filename) {
        return getExtend(filename, "");
    }

    /**
     * ???
     * 
     * @param filename
     * @return
     */
    public static String getExtend(String filename, String defExt) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');

            if ((i > 0) && (i < (filename.length() - 1))) {
                return (filename.substring(i + 1)).toLowerCase();
            }
        }
        return defExt.toLowerCase();
    }

    /**
     * ???[?????]
     * 
     * @param
     * @return String
     */
    public static String getFilePrefix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(0, splitIndex).replaceAll("\\s*", "");
    }

    /**
     * ???[?????]
     * ?
     * @param
     * @return String
     */
    public static String getFilePrefix2(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(0, splitIndex);
    }

    public static String formetFileSize(long fileS) {// ??
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    public static void main(String[] args) {
        //System.out.println(formetFileSize(755996)); ;
        String s = "D:\\work\\app_server\\tomcat-7.0.55\\temp\\backup\\";
        String t = "D:\\work\\app_server\\tomcat-7.0.55\\webapps\\ieasy\\attached\\ueditor\\";
        String t1 = "D:\\work\\app_server\\tomcat-7.0.55\\webapps\\ieasy\\attached\\emp_touxiang\\";
        try {
            copyDirectoryToDirectory(new File(t), new File(s));
            copyDirectoryToDirectory(new File(t1), new File(s));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}