java进行文件的压缩(ZIP)

最近需要用到压缩,然后网上找了一些,自己又改了一些,写一下吧,希望有用的可以做一个参考

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipWar {
    
    public static void getZipWar(String path,String contextPath) {
        File fileFolder = new File(path);
        File[] listFiles = fileFolder.listFiles();
        String contextPathb = contextPath.substring(1, contextPath.length());
        try(ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream("D:\\"+contextPathb+".zip"))) {
            for (File file : listFiles) {
                getZipOutPutStreamEntryFile(zipOutputStream,file,contextPathb);
            }
            } catch (Exception e) {
                e.printStackTrace();
            } 
    }
    

    private static void getZipOutPutStreamEntryFile(ZipOutputStream zipOutputStream, File file,String contextPath) throws Exception {
        
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            for (File file2 : listFiles) {
                getZipOutPutStreamEntryFile(zipOutputStream, file2,contextPath);
            }
            
        } else {
            try {
                String path = file.getPath();
                //和TarOutputStream的TarEntry放的是File类型,这里放的是文件名
                String[] split = path.split(contextPath);
                ZipEntry zipEntry = new ZipEntry(path.substring(path.length()-split[2].length(), path.length()));
                zipOutputStream.putNextEntry(zipEntry);
                FileInputStream fileInputStream  = new FileInputStream(file.getPath());
                byte[] b = new byte[1024*1024*5];
                int length = 0;
                while ((length = fileInputStream.read(b)) != -1) {
                    zipOutputStream.write(b, 0, length);
                }
                
                fileInputStream.close();
                zipOutputStream.closeEntry();
                //调用了这个方法之后,后面的文件是不能被添加的,压缩包里面只有第一个文件,
//            gzipOutputStream.finish();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

==============================================================================================

调用:

        String path = rootPath+"/WEB-INF/resource/file/"+attribute.getDomain_name();
        String contextPathb = req.getContextPath().substring(1, req.getContextPath().length());
        /*ZipWar.getZipWar(path,contextPathb);*/
        WarZip.zip(path,contextPathb);

猜你喜欢

转载自blog.csdn.net/ilhxasll/article/details/82768842
今日推荐