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");
    }

猜你喜欢

转载自blog.csdn.net/weixin_39222112/article/details/82665202