zoukankan      html  css  js  c++  java
  • Apache Compress-使用

    Apache Compress 是什么?

      Apache  提供的文件压缩工具。

    运行环境

      jdk 1.7

      commons-compress 1.15

    测试代码

      

     1 package com.m.basic;
     2 
     3 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
     4 import org.junit.Test;
     5 
     6 import java.io.*;
     7 import java.util.zip.ZipOutputStream;
     8 
     9 public class CompressTest {
    10     
    11     @Test
    12     public void compressTest() {
    13         File targetFile = new File("D:/malin/malin.zip");
    14         File sourceFile = new File("D:/malin/xxx");
    15 
    16         compressFile(targetFile, sourceFile);
    17     }
    18 
    19     public void compressFile(File targetFile, File sourceFile) {
    20         ZipOutputStream zipOutput = null;
    21         try {
    22             zipOutput = new ZipOutputStream(new FileOutputStream(targetFile));
    23             compress(zipOutput, sourceFile, sourceFile.getName());
    24         } catch (Exception e) {
    25             e.printStackTrace();
    26         } finally {
    27             if (zipOutput != null) {
    28                 try {
    29                     zipOutput.closeEntry();
    30                     zipOutput.close();
    31                 } catch (IOException e) {
    32                     e.printStackTrace();
    33                 }
    34             }
    35         }
    36     }
    37 
    38     private void compress(ZipOutputStream zipOutput, File sourceFile, String base) throws IOException {
    39         if (sourceFile.isDirectory()) {
    40             File[] files = sourceFile.listFiles();
    41             if (files.length == 0) {
    42                 System.out.println(base + "/");
    43                 zipOutput.putNextEntry(new ZipArchiveEntry(base + "/"));
    44             } else {
    45                 for (File file : files) {
    46                     compress(zipOutput, file, base + "/" + file.getName());
    47                 }
    48             }
    49         } else {
    50             zipOutput.putNextEntry(new ZipArchiveEntry(base));
    51             FileInputStream fis = new FileInputStream(sourceFile);
    52             BufferedInputStream bis = new BufferedInputStream(fis);
    53 
    54             int tag;
    55             System.out.println(base);
    56             while ((tag = bis.read()) != -1) {
    57                 zipOutput.write(tag);
    58             }
    59             fis.close();
    60             bis.close();
    61         }
    62     }
    63 }
    View Code

    参考

    http://commons.apache.org/proper/commons-compress/examples.html

  • 相关阅读:
    IO之同步、异步、阻塞、非阻塞 (2)
    IO之同步、异步、阻塞、非阻塞
    Syncthing源码解析
    Syncthing源码解析
    在Gogland里对GO程序进行单元测试!
    GO学习笔记
    GO学习笔记
    GO学习笔记
    GO学习笔记
    GO学习笔记
  • 原文地址:https://www.cnblogs.com/linma/p/7826195.html
Copyright © 2011-2022 走看看