您可以为哈希图中的元素尝试custom serialization mechanism。
您要发送什么样的信息?里面的物体是什么样子的?
即使使用默认机制,并将所有不需要的属性标记为瞬态也会有所帮助。
此外,您可以尝试将您自己序列化的数据发送到ZipOutputStream,但我会将其作为最后一个资源,因为二进制内容不会压缩太多。
编辑
由于您只使用字符串,您可以创建一个包装器,其自定义序列化是一个压缩数组(就像 Peter Lawrey 的回答一样),但是,使用自定义序列化可以让您封装序列化过程并让它以某种方式“透明地工作” " 用于 RMI(RMI 序列化永远不会知道您使用的是压缩版本)
这是一个演示:
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class MapDemo implements Serializable {
private Map<String,String> map = new HashMap<String,String>();
// only for demo/comparison purposes, default would use compressoin always
private boolean useCompression;
public MapDemo( Map<String,String> map , boolean compressed ) {
this.map = map;
this.useCompression = compressed;
}
// This is the custom serialization using compression
private void writeObject(ObjectOutputStream out) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream os = useCompression ? new DeflaterOutputStream( baos ) : baos;
ObjectOutputStream oos = new ObjectOutputStream( os );
oos.writeObject( this.map );
oos.close();
out.write( baos.toByteArray() );
}
}
class Main {
public static void main( String [] args ) throws IOException {
Map<String,String> regular = new HashMap<String,String>();
Map<String,String> compressed = new HashMap<String,String>();
Random r = new Random();
for( int i = 0 ; i < 100000 ; i++ ) {
String key = ""+r.nextInt(1000000);
String value = ""+r.nextInt(1000000) ;
// put the same info
compressed.put( key , value );
regular.put( key , value );
}
save( new MapDemo( compressed, true ) , "map.compressed");
save( new MapDemo( regular, false ) , "map.regular");
}
private static void save( Object o, String toFile ) throws IOException {
// This is similar to what RMI serialization would do behind scenes
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(toFile));
oos.writeObject( o );
oos.close();
}
}