Java 读写GZIP格式文件代码
2018-07-20 来源:open-open
使用GZIP格式压缩文本以缩减文件大小,于是乎接触到了
GZIPInputStream/
GZIPOutputStream这两个类,还有
ByteArrayOutputStream这个类。这里写了一个简单的示例代码记录一下
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(); } } } } }
标签: 代码
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐