标签:
java中提供了对压缩格式的数据流的读写。它们封装到现成的IO 类中,以提供压缩功能。下面我们开始java中压缩文件的使用。
目录导航:
一、 Java中有着压缩的类:
二、 压缩库的一些说明:
三、 ZIP压缩的使用注意:
我们通过一个简单的程序用例来展开今天压缩类的使用讲解 ,程序结构如下
一、 我们创建一个GzipCompress类,用于GZIP压缩类的测试:首先是压缩文件方法compress():
// 压缩文件 private static void compress() throws Exception { BufferedReader in = new BufferedReader(new FileReader(("compress/test.txt"))); BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("uncompress/test.gz"))); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close(); }
二、 我们创建GZIP的解压缩方法:uncompress()
// 解压缩文件 private static void uncompress() throws Exception { BufferedReader in = new BufferedReader( new InputStreamReader(new GZIPInputStream(new FileInputStream("uncompress/test.gz")))); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); }
三、 在Main方法运行,得到如下结果:
一、 我们创建一个ZipCompress类,用于GZIP压缩类的测试:首先是压缩文件方法compress():压缩huhx.png,test2.txt, test3.txt, test4.txt文件
private final static String[] resources = new String[] { "huhx.png", "test2.txt", "test3.txt", "test4.txt" }; // 压缩文件 private static void compress() throws Exception { FileOutputStream f = new FileOutputStream("uncompress/test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of java zipping"); ZipEntry entry = null; for (String resource : resources) { System.out.println("writing file: " + resource); BufferedReader in = new BufferedReader(new FileReader("compress/" + resource)); entry = new ZipEntry(resource); entry.setComment(resource + " comments"); zos.putNextEntry(entry); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.flush(); } out.close(); System.out.println("checksum: " + csum.getChecksum().getValue()); }
二、 我们创建ZIP的解压缩方法:uncompress1()
// 解压缩文件 private static void uncompress1() throws Exception { FileInputStream fi = new FileInputStream("uncompress/test.zip"); CheckedInputStream csum = new CheckedInputStream(fi, new Adler32()); ZipInputStream in2 = new ZipInputStream(csum); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { System.out.println("reading file: " + ze.getName()); } System.out.println("checksum: " + csum.getChecksum().getValue()); bis.close(); }
三、 我们创建ZIP的解压缩另外一种方法:uncompress2()
// 解压缩文件 private static void uncompress2() throws Exception { ZipFile zf = new ZipFile("uncompress/test.zip"); Enumeration<?> e = zf.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); System.out.println("File: " + entry.getComment()); } zf.close(); }
四、 运行compress()和uncompress1()方法,得到结果如下:
五、 运行compress()和uncompress2()方法,得到结果如下:
http://www.cnblogs.com/huhx/p/javaCompress.html
标签:
原文地址:http://www.cnblogs.com/softidea/p/5308470.html