Java gzip文件读写

 

下面的是测试代码:

<textarea cols="50" rows="15" name="code" class="c-sharp">import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; public class Test { public static void main(String[] args) { readFileAndWriteGZip(); unZipFile(); } public static void readFileAndWriteGZip() { try { //打开需压缩文件作为文件输入流 FileInputStream fin = new FileInputStream("d:/test.txt"); //建立压缩文件输出流 FileOutputStream fout = new FileOutputStream("d:/test2.gzip"); //建立gzip压缩输出流 GZIPOutputStream gzout = new GZIPOutputStream(fout); //设定读入缓冲区尺寸 byte[] buf = new byte[1024]; int num; while ((num = fin.read(buf)) != -1) { gzout.write(buf,0,num); } gzout.close(); fout.close(); fin.close(); } catch (Exception ex) { System.err.println(ex.toString()); } } public static void unZipFile() { try { //建立grip压缩文件输入流 FileInputStream fin = new FileInputStream("d:/test2.gzip"); //建立gzip解压工作流 GZIPInputStream gzin = new GZIPInputStream(fin); //建立解压文件输出流 FileOutputStream fout = new FileOutputStream("d:/test2.txt"); byte[] buf=new byte[1024]; int num; while ((num = gzin.read(buf,0,buf.length)) != -1) { fout.write(buf,0,num); } gzin.close(); fout.close(); fin.close(); } catch (Exception ex){ System.err.println(ex.toString()); } } } </textarea>

 

测试通过。

 

参考:

http://www.bitscn.com/java/other/200605/24037.html

你可能感兴趣的:(Java gzip文件读写)