文件操作的工具类

相关代码如下:包含创建文件,创建目录,创建压缩文件,获取文件等相关操作。

public class FileUtil {

    private static final Log LOGGER = LogFactory.getLog(FileUtil.class);

    private static ArrayList<File> fileList = new ArrayList<File>();

    private static boolean  dirExist = false;

    public static boolean isDirExist() {
        return dirExist;
    }

    public static void setDirExist(boolean dirExist) {
        FileUtil.dirExist = dirExist;
    }
    /**
     * 读取指定目录下面的所有文件,
     * @param fileDir
     * @return
     */
    public static ArrayList<File> ReadFile(String fileDir) {
        if (!fileList.isEmpty()) {
            cleanFiles();
        }
        File[] files = new File(fileDir).listFiles();// 获取目录下的所有文件或文件夹
        if (files == null) {// 如果目录为空,直接退出
            return null;
        }
        // 遍历,目录下的所有文件
        for (File file : files) {
            if (file.isFile()) {
                fileList.add(file);
            } else if (file.isDirectory()) {
                ReadFile(file.getAbsolutePath());//采用递归的方式读取子文件里面的内容
            }
        }
        return fileList;
    }

    public static void cleanFiles() {
        fileList.clear();
    }
    /**
     * 把指定文件夹打包成zip格式的压缩包
     * @param sourceFilePath
     * @param zipFilePath
     * @param fileName
     * @return
     */
    public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {
        boolean flag = false;
        File sourceFile = new File(sourceFilePath);
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        if (!sourceFile.exists()) {
            LOGGER.error("待压缩的文件目录:" + sourceFilePath + "不存在.");
        } else {
            try {
                File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
                if (zipFile.exists()) {
                    LOGGER.info(zipFilePath + "目录下已经存在名字为:" + fileName + ".zip" + "打包文件.");
                } else {
                    File[] sourceFiles = sourceFile.listFiles();
                    if (sourceFiles == null || sourceFiles.length < 1) {
                        LOGGER.info("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
                    } else {
                        fos = new FileOutputStream(zipFile);
                        zos = new ZipOutputStream(new BufferedOutputStream(fos));
                        byte[] bufs = new byte[1024 * 10];
                        for (int i = 0; i < sourceFiles.length; i++) {
                            // 创建ZIP实体,并添加进压缩包
                            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
                            zos.putNextEntry(zipEntry);
                            // 读取待压缩的文件并写进压缩包里
                            fis = new FileInputStream(sourceFiles[i]);
                            bis = new BufferedInputStream(fis, 1024 * 10);
                            int read = 0;
                            while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                                zos.write(bufs, 0, read);
                                zos.flush();
                            }
                        }
                        flag = true;
                    }
                }
            } catch (FileNotFoundException e) {
                LOGGER.error(e.getMessage(), e);
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            } finally {
                try {
                    if (null != bis)
                        bis.close();
                    if (null != zos)
                        zos.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        return flag;
    }

    /**
     * 创建指定目录
     * @param destDirName
     * @return
     */
    public static boolean createDir(String destDirName) {
        dirExist  = true;
        File dir = new File(destDirName);
        if (dir.exists()) {
            return false;
        }
        // 创建目录
        if (dir.mkdirs()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 创建指定文件
     * @param destFilePath 
     * @return
     */
    public static File createFile(String destFilePath) {
        File file = new File(destFilePath);
        if (file.exists()) {
            System.out.println("创建文件" + destFilePath + "失败,目标文件已存在!");
            return file;
        }
        if (!file.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在,则创建父目录
            if (!file.getParentFile().mkdirs()) {
                LOGGER.error("创建目标文件所在目录失败!");
            }
        }
        try {
            if (file.createNewFile()) {
                return file;
            } 
        } catch (IOException e) {
            LOGGER.error("创建目标文件失败!" + e);
        }
        return file;
    }
    
    /**
     * 把指定内容写入文件
     * @param type 字段名
     * @param audioId
     * @param info
     * @param csspFilePath 路径
     */
    public static void writeToFile(String testWorkId, String type, int audioId, String info, String csspFilePath) {
        String fileName = csspFilePath.substring(csspFilePath.lastIndexOf('/') + 1, csspFilePath.lastIndexOf('.'));
        String destDir = "resultInfo/" + testWorkId + "/";
        if (FileUtil.createDir(destDir)) {//如果没目录则创建一个
            write(type, info, fileName, destDir);
        } else {
            write(type, info, fileName, destDir);
        }
    }

    private static void write(String type, String info, String fileName, String destDir) {
        File files = new File(destDir + fileName + ".txt");
        FileWriter fw = null;
        try {
            fw = new FileWriter(files, true);
            fw.write(type + ":" + info.toString() + "

");
            fw.flush();
        } catch (IOException e) {
            LOGGER.error(e);
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    LOGGER.error("写入文件失败");
                }
            }
        }
    }

}
原文地址:https://www.cnblogs.com/studyCenter/p/7354180.html