java文件压缩 zip gz

本文深入探讨了Java环境下文件压缩技术,包括多文件压缩和GZIP压缩流程,通过代码实例展示了如何使用ZipOutputStream进行多文件压缩,并通过GZIPOutputStream实现文件的GZIP压缩,最后介绍了如何从压缩文件中读取和解压数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
* 多文件压缩
*
* @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();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值