分享

Java Zip多文件压缩和 GZIP压缩

 昵称9552892 2012-11-08
/**
 * 多文件压缩
 * 
 * @author Administrator
 * 
 */
public class ZipCompress {

public static void main(String args[]) {
String[] filepaths = { "D:\\zip1.txt", "D:\\zip2.txt" };
try {
FileOutputStream f = new FileOutputStream("D://test.zip");
// 输出校验流,采用Adler32更快
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
//创建压缩输出流
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out = new BufferedOutputStream(zos);
//设置Zip文件注释
zos.setComment("A test of java Zipping");
for (String s : filepaths) {
System.out.println("Writing file " + s);
//针对单个文件建立读取流
BufferedReader bin = new BufferedReader(new FileReader(s));
//ZipEntry ZIP 文件条目
//putNextEntry 写入新条目,并定位到新条目开始处
zos.putNextEntry(new ZipEntry(s));
int c;
while ((c = bin.read()) != -1) {
out.write(c);
}
bin.close();
out.flush();
}
out.close();
FileInputStream fi = new FileInputStream("D://test.zip");
CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis = new BufferedInputStream(in2);
ZipEntry ze;
while ((ze = in2.getNextEntry()) != null) {
System.out.println("Reader File " + ze);
int x;
while ((x = bis.read()) != -1)
System.out.println(x);
}
//利用ZipFile解压压缩文件
ZipFile zf = new ZipFile("D:\\test.zip");
Enumeration e = zf.entries();
while(e.hasMoreElements()){
ZipEntry ze2 = (ZipEntry) e.nextElement();
System.out.println("File name : "+ze2);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**  
 * 文件压缩  
 * 把文件压缩成GZIP 单一的流数据 并不是互异的数据  
 * GZIPOutputStream的使用  
 * @author Administrator  
 *   
 */  
public class GzipPcompress {   
  
    public static void main(String args[]) {   
        try {   
            BufferedReader in = new BufferedReader(new FileReader("D:\\gziptest.txt"));   
  
            BufferedOutputStream out = new BufferedOutputStream(   
                    new GZIPOutputStream(new FileOutputStream("D:\\test.gz")));   
            System.out.println("Writing file");   
            int c;   
            while ((c = in.read()) != -1) {   
                out.write(c);   
            }   
            in.close();   
            out.close();   
            System.out.println("Reading file");   
            BufferedReader in2 = new BufferedReader(new InputStreamReader(   
                    new GZIPInputStream(new FileInputStream("D:\\test.gz"))));   
            String s;   
            while((s=in2.readLine()) != null){   
                System.out.println(s);   
            }   
  
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    }   
}   

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多