KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > test_deflate_inflate


1 /* -*-mode:java; c-basic-offset:2; -*- */
2 import java.io.*;
3 import com.jcraft.jzlib.*;
4
5 // Test deflate() with small buffers
6

7 class test_deflate_inflate{
8
9   static final byte[] hello="hello, hello! ".getBytes();
10   static{
11     hello[hello.length-1]=0;
12   }
13
14   public static void main(String JavaDoc[] arg){
15     int err;
16     int comprLen=40000;
17     int uncomprLen=comprLen;
18     byte[] compr=new byte[comprLen];
19     byte[] uncompr=new byte[uncomprLen];
20
21     ZStream c_stream=new ZStream();
22
23     err=c_stream.deflateInit(JZlib.Z_DEFAULT_COMPRESSION);
24     CHECK_ERR(c_stream, err, "deflateInit");
25
26     c_stream.next_in=hello;
27     c_stream.next_in_index=0;
28
29     c_stream.next_out=compr;
30     c_stream.next_out_index=0;
31
32     while(c_stream.total_in!=hello.length &&
33       c_stream.total_out<comprLen){
34       c_stream.avail_in=c_stream.avail_out=1; // force small buffers
35
err=c_stream.deflate(JZlib.Z_NO_FLUSH);
36       CHECK_ERR(c_stream, err, "deflate");
37     }
38
39     while(true){
40       c_stream.avail_out=1;
41       err=c_stream.deflate(JZlib.Z_FINISH);
42       if(err==JZlib.Z_STREAM_END)break;
43       CHECK_ERR(c_stream, err, "deflate");
44     }
45
46     err=c_stream.deflateEnd();
47     CHECK_ERR(c_stream, err, "deflateEnd");
48
49     ZStream d_stream=new ZStream();
50
51     d_stream.next_in=compr;
52     d_stream.next_in_index=0;
53     d_stream.next_out=uncompr;
54     d_stream.next_out_index=0;
55
56     err=d_stream.inflateInit();
57     CHECK_ERR(d_stream, err, "inflateInit");
58
59     while(d_stream.total_out<uncomprLen &&
60       d_stream.total_in<comprLen) {
61       d_stream.avail_in=d_stream.avail_out=1; /* force small buffers */
62       err=d_stream.inflate(JZlib.Z_NO_FLUSH);
63       if(err==JZlib.Z_STREAM_END) break;
64       CHECK_ERR(d_stream, err, "inflate");
65     }
66
67     err=d_stream.inflateEnd();
68     CHECK_ERR(d_stream, err, "inflateEnd");
69
70     int i=0;
71     for(;i<hello.length; i++) if(hello[i]==0) break;
72     int j=0;
73     for(;j<uncompr.length; j++) if(uncompr[j]==0) break;
74
75     if(i==j){
76       for(i=0; i<j; i++) if(hello[i]!=uncompr[i]) break;
77       if(i==j){
78     System.out.println("inflate(): "+new String JavaDoc(uncompr, 0, j));
79     return;
80       }
81     }
82     else{
83       System.out.println("bad inflate");
84     }
85   }
86
87   static void CHECK_ERR(ZStream z, int err, String JavaDoc msg) {
88     if(err!=JZlib.Z_OK){
89       if(z.msg!=null) System.out.print(z.msg+" ");
90       System.out.println(msg+" error: "+err);
91       System.exit(1);
92     }
93   }
94 }
95
Popular Tags