在文件的傳輸過程中,為了使大文件能夠更加方便快速的傳輸,一般采用壓縮的辦法來對文件壓縮後再傳輸,JAVA中的java.util.zip包中的Deflater和Inflater類為使用者提供了DEFLATE算法的壓縮功能,以下是自已編寫的壓縮和解壓縮實現,並以壓縮文件內容為例說明,其中涉及的具體方法可查看JDK的API了解說明。
1 /**
2 *
3 * @param inputByte
4 * 待解壓縮的字節數組
5 * @return 解壓縮後的字節數組
6 * @throws IOException
7 */
8 public static byte[] uncompress(byte[] inputByte) throws IOException {
9 int len = 0;
10 Inflater infl = new Inflater();
11 infl.setInput(inputByte);
12 ByteArrayOutputStream bos = new ByteArrayOutputStream();
13 byte[] outByte = new byte[1024];
14 try {
15 while (!infl.finished()) {
16 // 解壓縮並將解壓縮後的內容輸出到字節輸出流bos中
17 len = infl.inflate(outByte);
18 if (len == 0) {
19 break;
20 }
21 bos.write(outByte, 0, len);
22 }
23 infl.end();
24 } catch (Exception e) {
25 //
26 } finally {
27 bos.close();
28 }
29 return bos.toByteArray();
30 }
31
32 /**
33 * 壓縮.
34 *
35 * @param inputByte
36 * 待壓縮的字節數組
37 * @return 壓縮後的數據
38 * @throws IOException
39 */
40 public static byte[] compress(byte[] inputByte) throws IOException {
41 int len = 0;
42 Deflater defl = new Deflater();
43 defl.setInput(inputByte);
44 defl.finish();
45 ByteArrayOutputStream bos = new ByteArrayOutputStream();
46 byte[] outputByte = new byte[1024];
47 try {
48 while (!defl.finished()) {
49 // 壓縮並將壓縮後的內容輸出到字節輸出流bos中
50 len = defl.deflate(outputByte);
51 bos.write(outputByte, 0, len);
52 }
53 defl.end();
54 } finally {
55 bos.close();
56 }
57 return bos.toByteArray();
58 }
59
60 public static void main(String[] args) {
61 try {
62 FileInputStream fis = new FileInputStream("D:\\testdeflate.txt");
63 int len = fis.available();
64 byte[] b = new byte[len];
65 fis.read(b);
66 byte[] bd = compress(b);
67 // 為了壓縮後的內容能夠在網絡上傳輸,一般采用Base64編碼
68 String encodestr = Base64.encodeBase64String(bd);
69 byte[] bi = uncompress(Base64.decodeBase64(encodestr));
70 FileOutputStream fos = new FileOutputStream("D:\\testinflate.txt");
71 fos.write(bi);
72 fos.flush();
73 fos.close();
74 fis.close();
75 } catch (Exception e) {
76 //
77 }
78 }