添加Kryo工具包:
<!-- https://mvnrepository.com/artifact/com.esotericsoftware/kryo -->
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>4.0.1</version>
</dependency>
反序列化
package cn.com.xy.sms.sdk.Iservice;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.xy.file.uitl.FileUtil;
public class KryoUtil {
/**
*
* @param filepath
* @param obj
* 需序列化的 JAVA 基础对象,List Map
*/
public static void writeKryo(String filepath, String fileName, Object obj) {
OutputStream os = null;
Output output = null;
try {
File file = new File(filepath);
if (!file.exists()) {
FileUtil.createDier(filepath);
}
file = new File(filepath + fileName);
if (!file.exists()) {
file.createNewFile();
}
os = new FileOutputStream(file);
output = new Output(os);// kryo序列化输出流
KryoSingleton.getInstance().writeClassAndObject(output, obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(output, os);
}
}
public static <T> T readKryo(String filepath) {
InputStream is = null;
Input input = null;
T o = null;
try {
is = new FileInputStream(filepath);
input = new Input(is, 1024 * 2);
o = (T) KryoSingleton.getInstance().readClassAndObject(input);
} catch (IOException e) {
throw new IllegalAccessError(e.getMessage());
} finally {
close(is, input);
}
return o;
}
/**
* 关闭Closeable
*
* @param iss
*/
public static void close(Closeable... iss) {
for (Closeable is : iss) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
/**
* 序列化
*
* @param filepath
* @param obj
* @param kryo
*/
public static void writeKryo(String filepath, Object obj, Kryo kryo) {
OutputStream os = null;
Output output = null;
try {
File file = new File(filepath);
os = new FileOutputStream(file);
output = new Output(os);// kryo序列化输出流
kryo.writeClassAndObject(output, obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(output, os);
}
}
}
获取序列化/反序列化种初始化的类对应Kryo
package cn.com.xy.sms.sdk.Iservice;
import com.esotericsoftware.kryo.Kryo;
public class KryoSingleton{
private KryoSingleton(){}
public static Kryo getInstance(){
return Singleton.INSTANCE.getInstance();
}
private static enum Singleton{
INSTANCE;
private Kryo singleton;
//JVM会保证此方法绝对只调用一次
private Singleton(){
singleton = new Kryo();
// 如果没有多层次的对象引用相互引用,设为false,提高性能
singleton.setReferences(false);
// 注册序列化/反序列化的类
singleton.register(SceneLayout.class);
singleton.register(SceneLayoutMethod.class);
}
public Kryo getInstance(){
return singleton;
}
}
}