JAVA中的deflate緊縮完成辦法。本站提示廣大學習愛好者:(JAVA中的deflate緊縮完成辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是JAVA中的deflate緊縮完成辦法正文
在文件的傳輸進程中,為了使年夜文件可以或許加倍便利疾速的傳輸,普通采取緊縮的方法來對文件緊縮後再傳輸,JAVA中的java.util.zip包中的Deflater和Inflater類為應用者供給了DEFLATE算法的緊縮功效,以下是自已編寫的緊縮息爭緊縮完成,並以緊縮文件內容為例解釋,個中觸及的詳細辦法可檢查JDK的API懂得解釋。
/**
*
* @param inputByte
* 待解緊縮的字節數組
* @return 解緊縮後的字節數組
* @throws IOException
*/
public static byte[] uncompress(byte[] inputByte) throws IOException {
int len = 0;
Inflater infl = new Inflater();
infl.setInput(inputByte);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] outByte = new byte[1024];
try {
while (!infl.finished()) {
// 解緊縮並將解緊縮後的內容輸入到字節輸入流bos中
len = infl.inflate(outByte);
if (len == 0) {
break;
}
bos.write(outByte, 0, len);
}
infl.end();
} catch (Exception e) {
//
} finally {
bos.close();
}
return bos.toByteArray();
}
/**
* 緊縮.
*
* @param inputByte
* 待緊縮的字節數組
* @return 緊縮後的數據
* @throws IOException
*/
public static byte[] compress(byte[] inputByte) throws IOException {
int len = 0;
Deflater defl = new Deflater();
defl.setInput(inputByte);
defl.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] outputByte = new byte[1024];
try {
while (!defl.finished()) {
// 緊縮並將緊縮後的內容輸入到字節輸入流bos中
len = defl.deflate(outputByte);
bos.write(outputByte, 0, len);
}
defl.end();
} finally {
bos.close();
}
return bos.toByteArray();
}
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D:\\testdeflate.txt");
int len = fis.available();
byte[] b = new byte[len];
fis.read(b);
byte[] bd = compress(b);
// 為了緊縮後的內容可以或許在收集上傳輸,普通采取Base64編碼
String encodestr = Base64.encodeBase64String(bd);
byte[] bi = uncompress(Base64.decodeBase64(encodestr));
FileOutputStream fos = new FileOutputStream("D:\\testinflate.txt");
fos.write(bi);
fos.flush();
fos.close();
fis.close();
} catch (Exception e) {
//
}
}
以上這篇JAVA中的deflate緊縮完成辦法就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。