歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中的deflate算法實現壓縮功能

Java中的deflate算法實現壓縮功能

日期:2017/3/1 9:12:26   编辑:Linux編程

在文件的傳輸過程中,為了使大文件能夠更加方便快速的傳輸,一般采用壓縮的辦法來對文件壓縮後再傳輸,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) {
//
}
}

Copyright © Linux教程網 All Rights Reserved