java文件壓縮ZipOutPutStream


其實最好的書籍就是javaAPI

1.創建ZipOutPutStream流,利用BufferedOutputStream提個速.

2.新建zip方法,用來壓縮文件,傳參

3.zip方法利用putNextEntry來將目錄點寫入

4.遞歸目錄數組

5.寫入數據,關閉流

 

/**
 * 壓縮
 * @author BinPeng
 * @date 2019/8/6 18:19
 */
public class Zip18 {
    public static void main(String[] args) throws IOException {
        compreSsion("F:\\test.zip",new File("F:\\test"));//第一個參數是壓縮的名字,第二個參數是要壓縮的目錄
    }
    private static void compreSsion(String zipFileName, File target) throws IOException {//壓縮
        System.out.println("壓縮文件...");
        ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName));
        BufferedOutputStream bos=new BufferedOutputStream(out);
        zip(out,target,target.getName(),bos);
        bos.close();
        out.close();
        System.out.println("壓縮完成");
    }

    private static void zip(ZipOutputStream zout, File target, String name, BufferedOutputStream bos) throws IOException {
        //判斷是不是目錄
        if (target.isDirectory()){
          File[] files=target.listFiles();
          if (files.length==0){//空目錄
              zout.putNextEntry(new ZipEntry(name+"/"));
            /*  開始編寫新的ZIP文件條目,並將流定位到條目數據的開頭。
              關閉當前條目,如果仍然有效。 如果沒有為條目指定壓縮方法,
              將使用默認壓縮方法,如果條目沒有設置修改時間,將使用當前時間。*/
          }
          for (File f:files){
              //遞歸處理
              zip(zout,f,name+"/"+f.getName(),bos);
          }
        }else {
                zout.putNextEntry(new ZipEntry(name));
                InputStream inputStream=new FileInputStream(target);
                BufferedInputStream bis=new BufferedInputStream(inputStream);
                byte[] bytes=new byte[1024];
                int len=-1;
                while ((len=bis.read(bytes))!=-1){
                    bos.write(bytes,0,len);
                }
                bis.close();

        }

    }

}

  

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM