欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java需要关注的知识点---I0之压缩

程序员文章站 2022-03-23 14:55:51
...
1.GZIP压缩:

public class GZIPPcompress {
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Usage: \n GZIPcompress file\n" +
" \tUses GZIP compresion to compress " +
" the file to test.gz");
System.exit(1);
}
BufferedReader in = new BufferedReader(new FileReader(args[0]));
BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("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("test.gz"))));
String s;
while((s = in2.readLine()) != null) {
System.out.println(s);
}
}
}

ZIP压缩文件:

package com.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipCompress {
public static void main(String[] args) throws IOException {
FileOutputStream f = new FileOutputStream("test.zip");
CheckedOutputStream cos = new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(cos);
BufferedOutputStream out = new BufferedOutputStream(zos);
zos.setComment("A test of Java Zipping");
for(String arg:args) {
System.out.println("Writing file " + arg);
zos.putNextEntry(new ZipEntry(arg));
BufferedReader in = new BufferedReader(new FileReader(arg));
int c;
while((c = in.read()) != -1) {
out.write(c);
}
out.flush();

}
out.close();
System.out.println("Checksum:" + cos.getChecksum().getValue());
System.out.println("Reading file!");
FileInputStream fi = new FileInputStream("test.zip");
CheckedInputStream cis = new CheckedInputStream(fi, new Adler32());
ZipInputStream zis = new ZipInputStream(cis);
BufferedInputStream bis = new BufferedInputStream(zis);
ZipEntry ze;
while((ze = zis.getNextEntry()) != null) {
System.out.println("Read file:" +ze);
int x;
while((x = bis.read()) != -1) {
System.out.write(x);
}
System.out.println();
}
if(args.length == 1) {
System.out.println("Check Sum:" + cis.getChecksum().getValue());
ZipFile zf = new ZipFile("test.zip");
Enumeration e = zf.entries();
while(e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry) e.nextElement();
System.out.println("File:" + ze2);
}
}
}

}

相关标签: gzip