Posted on 2007-04-10 21:29
chenweicai 阅读(591)
评论(0) 编辑 收藏
类Deflater 和 类Inflater:此类使用流行的 ZLIB 压缩程序库为通用压缩提供支持。ZLIB 压缩程序库最初是作为 PNG 图形标准的一部分开发的,不受专利的保护。
//encoding a string into bytes
String inputString = "chenweicai";
byte[] input = inputString.getBytes("UTF-8");
System.out.println("before compressed, the bytes length is :" + input.length);
//compress the bytes
byte[] output = new byte[100];
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
System.out.println("compressed bytes length is :" + compressedDataLength);
//decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(output, 0, compressedDataLength);
byte[] result = new byte[100];
int resultLength = decompresser.inflate(result);
decompresser.end();
System.out.println("after decompressed, the bytes length is :" + resultLength);
//decode the bytes into a string
String outputString = new String(result, 0, resultLength, "UTF-8");
System.out.println("after compress and decompress the string is :" + outputString);
2.
import java.io.Serializable;
public class Employee implements Serializable {
private String name;
private double salary;
public Employee(String name, double salary) {
super();
// TODO Auto-generated constructor stub
this.name = name;
this.salary = salary;
}
public void raiseSalary(double byPercent){
double temp = salary * byPercent / 100;
salary += temp;
}
public String toString() {
// TODO Auto-generated method stub
return getClass().getName() +
"[ Name = " + name + ", salary = " + salary +"]";
}
}
public class Test2 {
protected byte[] deflate(Object object) throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Deflater def = new Deflater (Deflater.BEST_COMPRESSION);
DeflaterOutputStream dos = new DeflaterOutputStream(baos, def);
ObjectOutputStream out = new ObjectOutputStream(dos);
out.writeObject(object);
out.close();
dos.finish();
dos.close();
return baos.toByteArray();
}
protected Object inflate(byte[] compressedContent) throws IOException{
if(compressedContent == null)
return null;
try{
ObjectInputStream in = new ObjectInputStream(
new InflaterInputStream(new ByteArrayInputStream(compressedContent)));
Object object = in.readObject();
in.close();
return object;
}catch(Exception e){
throw new IOException(e.toString());
}
}
public static void main(String[] args) throws IOException{
Employee employee = new Employee("LiLei", 1000);
Test2 test2 = new Test2();
byte[] bytes = new byte[1000];
bytes = test2.deflate(employee);
System.out.println(bytes);
System.out.println(test2.inflate(bytes));
}
}