1. 程式人生 > >Java最簡單的實現壓縮檔案

Java最簡單的實現壓縮檔案

都是用Java最基本的api實現的,廢話不多直接上程式碼

public class ZipUtils {

   //供外部類呼叫的方法 引數1原始檔路徑   引數2 目標檔案路徑
    public static void toZip(String srcPath, String targetPath) {
        File srcFile = new File(srcPath);
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(targetPath);
            zos = new ZipOutputStream(fos);
            compress(srcFile, zos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

   //實現遞迴壓縮
    private static void compress(File srcFile,ZipOutputStream zos) throws Exception {
        byte[] b = new byte[2048];
        if(srcFile.isFile()) {
            int len = 0;
            zos.putNextEntry(new ZipEntry(srcFile.getName()));
            FileInputStream fis = new FileInputStream(srcFile);
            while((len = fis.read(b)) != -1) {
                zos.write(b, 0, len);
            }
            zos.closeEntry();
            fis.close();    
        } else {
            File files[] = srcFile.listFiles();
            for(File file:files) {
                compress(file, zos);
            }
        }
        
    }
    public static void main(String[] args) {
        toZip("原始檔", "目標檔案.zip");
    }