AndroidTools:文件工具-壓縮文件

AndroidTolls Git地址:https://github.com/wisesun7/AndroidTools.git

     本篇提供了一些壓縮文件的方法,可對單個或批量文件(夾)進行壓縮。

**
 * Created by wise on 2019/6/19.
 * {@link #zipFile(File, ZipOutputStream, String)}
 * {@link #zipFiles(Collection, File)}
 * {@link #zipFiles(Collection, File, String)}
 */

public class ZipUtils {
    private static final int BUFF_SIZE = 1024 * 1024;  //1M

    /**
     * 批量壓縮文件(夾)
     *
     * @param resFileList 要壓縮的文件(夾)列表
     * @param zipFile 生成的壓縮文件
     * @throws IOException 當壓縮過程出錯時拋出
     */
    public static void zipFiles(Collection<File> resFileList, File zipFile) throws IOException {
        ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
        for (File resFile : resFileList) {
            zipFile(resFile, zipout, "");
        }
        zipout.close();
    }


    /**
     * 批量壓縮文件(夾)
     *
     * @param resFileList 要壓縮的文件(夾)列表
     * @param zipFile 生成的壓縮文件
     * @param comment 壓縮文件的註釋
     * @throws IOException 當壓縮過程出錯時拋出
     */
    public static void zipFiles(Collection<File> resFileList, File zipFile, String comment) throws IOException {
        ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
        for (File resFile : resFileList) {
            zipFile(resFile, zipout, "");
        }
        zipout.setComment(comment);
        zipout.close();
    }


    /**
     * 壓縮文件
     *
     * @param resFile 需要壓縮的文件(夾)
     * @param zipout 壓縮的目的文件
     * @param rootpath 壓縮的文件路徑
     * @throws FileNotFoundException 找不到文件時拋出
     * @throws IOException 當壓縮過程出錯時拋出
     */
    private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException {
        rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator)+ resFile.getName();
        rootpath = new String(rootpath.getBytes("8859_1"), "GB2312");
        if (resFile.isDirectory()) {
            File[] fileList = resFile.listFiles();
            if (fileList != null) {
                for (File file : fileList) {
                    zipFile(file, zipout, rootpath);
                }
            }
        } else {
            byte buffer[] = new byte[BUFF_SIZE];
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile),BUFF_SIZE);
            zipout.putNextEntry(new ZipEntry(rootpath));
            int realLength;
            while ((realLength = in.read(buffer)) != -1) {
                zipout.write(buffer, 0, realLength);
            }
            in.close();
            zipout.flush();
            zipout.closeEntry();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章