Java 读写GZIP格式文件

      最近的工作中需要使用GZIP格式压缩文本以缩减文件大小,于是乎接触到了GZIPInputStream/GZIPOutputStream这两个类,还有ByteArrayOutputStream这个类。这里写了一个简单的示例代码记录一下,以备不时之需。


package com.ricky.java.test.junit;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipFileTest {
	
	private static final int BUFFER_SIZE = 1024;
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		File inputFile = new File("D:/test/input.txt");
		
		File outputFile = new File("D:/test/test.dat");
		
		writeGZip(inputFile,outputFile);
		
		readGZip(outputFile);
	}

	public static void readGZip(File file) {
		
		GZIPInputStream gzipInputStream = null;
		ByteArrayOutputStream baos = null;
		try {
			gzipInputStream = new GZIPInputStream(new FileInputStream(file));
			
			baos = new ByteArrayOutputStream();
			
			byte[] buf = new byte[BUFFER_SIZE];
			int len = 0;
			while((len=gzipInputStream.read(buf, 0, BUFFER_SIZE))!=-1){
				baos.write(buf, 0, len);
			}
			
			baos.toByteArray();
			
			String result = baos.toString("UTF-8");
			
			System.out.println("result="+result);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(gzipInputStream!=null){
				try {
					gzipInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(baos!=null){
				try {
					baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void writeGZip(File inputFile, File outputFile) {
		
		GZIPOutputStream gzipOutputStream = null;
		InputStream in = null;
		try {
			gzipOutputStream = new GZIPOutputStream(new FileOutputStream(outputFile));
			
			in = new FileInputStream(inputFile);
			
			byte[] buffer = new byte[BUFFER_SIZE];

			int len = 0;
			while ((len = in.read(buffer,0,BUFFER_SIZE)) > 0) {
				gzipOutputStream.write(buffer, 0, len);
			}
			gzipOutputStream.finish();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(gzipOutputStream!=null){
				try {
					gzipOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}






你可能感兴趣的:(Java)