文件的压缩
Java I/O类库中的类支持读写压缩格式的数据流。可以用它们对其他的I/O类进行封装,以提供压缩功能。
这些类不是从Reader和Writer类派生而来的,而是属于InputStream和OutputStream继承层次结构的一部分,这样做是因为压缩类库是按字节的方式而不是按字符的方式处理的。
package solutions; import java.io.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Created by Administrator on 2016/3/14. */ public class GZIPcompress { public static void main(String[] args) throws IOException{ if(args.length==0){ System.out.println("Usage: GZIPcompress file " + " Uses GZIP compression 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进行多文件的保存
支持Zip格式的Java库更加全面,利用该库可以方便地保存多个文件,它甚至有一个独立的类,使得读取Zip文件更加方便
package solutions; import java.io.*; import java.util.zip.*; /** * Created by Administrator on 2016/3/14. */ public class ZipCompress { public static void main(String[] args) throws IOException{ //1.写文件(压缩文件) FileOutputStream f=new FileOutputStream("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"); for(String arg:args){ System.out.print("writing file"+arg); BufferedReader in=new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c=in.read())!=-1) out.write(c); in.close(); out.flush(); } out.close(); //2.读文件(解压文件) FileInputStream fi=new FileInputStream("tets.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){ int x; while ((x=bis.read())!=-1){ System.out.write(x); } bis.close(); } } }