📄 ziplist.java
字号:
package com.ufmobile.common.transport;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* <p>
* 对要传输的对象进行内存压缩
* <p>
* 创建日期:Jan 4, 2007
*
* @author msf
* @since v3.0
*/
public class ZipList<T> extends ArrayList<T> {
private int zipLever;
public ZipList() {
super();
}
public ZipList(int initialCapacity, int zipLever) {
super(initialCapacity);
this.zipLever = zipLever;
}
public ZipList(Collection<? extends T> c) {
super(c);
}
public ZipList(int initialCapacity) {
super(initialCapacity);
}
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
int expectedModCount = modCount;
// Write out element count, and any hidden stuff
s.defaultWriteObject();
// Write out array length
s.writeInt(size());
s.write(zipLever);
byte[] data=writeCompressObject();
s.writeInt(data.length);
s.writeObject(writeCompressObject());
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
zipLever=s.readInt();
int lenth=s.readInt();
byte[] data=new byte[lenth];
s.read(data) ;
readCompressObject(data,arrayLength);
}
private byte[] writeCompressObject() {
byte[] data_ = null;
try {
// 建立字节数组输出流
ByteArrayOutputStream byteout= new ByteArrayOutputStream();
// 建立gzip压缩输出流
ZipOutputStream zout = new ZipOutputStream(byteout);
zout.setLevel(zipLever);
// 建立对象序列化输出流
ObjectOutputStream out = new ObjectOutputStream(zout);
for (int i = 0; i < size(); i++)
out.writeObject(get(i));
out.flush();
out.close();
zout.close();
// 返回压缩字节流
data_ = byteout.toByteArray();
byteout.close();
} catch (IOException e) {
System.out.println(e);
}
return (data_);
}
private void readCompressObject(byte[] data_,int arrayLength) {
try {
// 建立字节数组输入流
ByteArrayInputStream bytein = new ByteArrayInputStream(data_);
// 建立gzip解压输入流
ZipInputStream gzin = new ZipInputStream(bytein);
// 建立对象序列化输入流
ObjectInputStream in = new ObjectInputStream(gzin);
// 按制定类型还原对象
for(int i=0;i<arrayLength;i++){
T object_ = (T) in.readObject();
}
bytein.close();
gzin.close();
in.close();
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (IOException e) {
System.out.println(e);
}
}
public int getZipLever() {
return zipLever;
}
public void setZipLever(int zipLever) {
this.zipLever = zipLever;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -