生活随笔
收集整理的這篇文章主要介紹了
java 使用gzip压缩和解压 传输文件必备
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java gzip 壓縮解壓工具類,開箱即用
gzip原理看我另外一篇介紹
壓縮效果直接看圖:
package com
.yeahmobi
.datacheck
.util
;import java
.io
.*
;
import java
.util
.zip
.GZIPInputStream
;
import java
.util
.zip
.GZIPOutputStream
;public class CompressUtil {public static void main(String
[] args
) throws IOException
{String inFileName
= "D:\\response.xls";compressFile(inFileName
);}public static void compressFile(String inFileName
) throws IOException
{FileInputStream in
= null
;GZIPOutputStream out
= null
;String outFileName
= inFileName
+ ".gz";try {in
= new FileInputStream(new File(inFileName
));} catch (FileNotFoundException e
) {throw new RuntimeException("文件不存在:" + inFileName
);}out
= new GZIPOutputStream(new FileOutputStream(outFileName
));byte[] buf
= new byte[10240];int len
= 0;if (in
!= null
&& out
!= null
) {try {while (((in
.available() > 10240) && (in
.read(buf
)) > 0)) {out
.write(buf
);}len
= in
.available();in
.read(buf
, 0, len
);out
.write(buf
, 0, len
);in
.close();out
.flush();out
.close();} catch (IOException e
) {throw new RuntimeException("壓縮失敗:" + inFileName
);}}in
.close();out
.close();}public static void doUncompressFile(String inFileName
) {try {if (!getExtension(inFileName
).equalsIgnoreCase("gz")) {throw new RuntimeException("文件名必須是gz后綴");}GZIPInputStream in
= null
;try {in
= new GZIPInputStream(new FileInputStream(inFileName
));} catch (FileNotFoundException e
) {throw new RuntimeException("文件不存在 " + inFileName
);}String outFileName
= getFileName(inFileName
);try (FileOutputStream out
= new FileOutputStream(outFileName
);) {byte[] buf
= new byte[1024];int len
;while ((len
= in
.read(buf
)) > 0) {out
.write(buf
, 0, len
);}in
.close();out
.close();} catch (FileNotFoundException e
) {throw new RuntimeException("解壓失敗" + outFileName
);}} catch (IOException e
) {throw new RuntimeException("失敗");}}public static String
getExtension(String f
) {String ext
= "";int i
= f
.lastIndexOf('.');if (i
> 0 && i
< f
.length() - 1) {ext
= f
.substring(i
+ 1);}return ext
;}public static String
getFileName(String f
) {String fname
= "";int i
= f
.lastIndexOf('.');if (i
> 0 && i
< f
.length() - 1) {fname
= f
.substring(0, i
);}return fname
;}
}
總結
以上是生活随笔為你收集整理的java 使用gzip压缩和解压 传输文件必备的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。