Java I/O 学习笔记(8) 文件压缩

来源:互联网 发布:苹果手机怎样更新淘宝 编辑:程序博客网 时间:2024/05/20 22:04
package files;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.CRC32;import java.util.zip.CheckedInputStream;import java.util.zip.CheckedOutputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;public class TestZipStream {/** * @param args * @throws IOException */public static void main(String[] args) throws IOException {testZipCompress("input.txt", "output.txt");testZipUncompress();}public static void testZipCompress(String... fileNames) throws IOException {FileOutputStream fos = new FileOutputStream("test.zip");CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32());ZipOutputStream zos = new ZipOutputStream(cos);BufferedOutputStream bos = new BufferedOutputStream(zos);zos.setComment(new String("测试压缩".getBytes("UTF-16BE")).intern());BufferedInputStream br = null;for (int i = 0; i < fileNames.length; i++) {br = new BufferedInputStream(new FileInputStream(fileNames[i]));zos.putNextEntry(new ZipEntry(fileNames[i]));int c = 0;while ((c = br.read()) != -1) {bos.write(c);}br.close();bos.flush();}System.out.println("Compress CRC32: " + cos.getChecksum().getValue());bos.close();}public static void testZipUncompress() throws IOException {FileInputStream fis = new FileInputStream("test.zip");CheckedInputStream cis = new CheckedInputStream(fis, new CRC32());ZipInputStream zis = new ZipInputStream(cis);BufferedInputStream bis = new BufferedInputStream(zis);BufferedOutputStream bos = null;ZipEntry ze = null;while ((ze = zis.getNextEntry()) != null) {System.out.println(ze);bos = new BufferedOutputStream(new FileOutputStream(ze.toString()+ ".txt"));int x = 0;while ((x = bis.read()) != -1) {bos.write(x);}bos.close();}System.out.println("Uncompress CRC32: " + cis.getChecksum().getValue());bis.close();}}

0 0
原创粉丝点击