在写自动化工具的时候经常遇到一个问题,工具前面历经坎坷做完了很多事情,但是在最后一步出错了,修改完之后要进行验证,你可能需要又重走一遍之前的步骤来拿到出现问题的场景,不得不说,这时候感觉很坑爹……
然后福利来了,我们知道java提供了序列化和反序列化机制,而另外还有很多此类序列化和反序列化框架,而protostuff则是在protobuff基础上改进的一个优秀代表。 那我们怎么用这个框架来做一些事情让调试这些事情不那么坑爹呢?
-
首先我们先引入依赖
1
2
3
4
5
6
7
8
9
10
11
|
< dependency >
< groupId >io.protostuff</ groupId >
< artifactId >protostuff-core</ artifactId >
< version >1.3.3</ version >
</ dependency >
< dependency >
< groupId >io.protostuff</ groupId >
< artifactId >protostuff-runtime</ artifactId >
< version >1.3.3</ version >
</ dependency >
|
-
将java对象转化为byte数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public byte []
serializeProtoStuffReport(PerformanceReport report) {
Schema<PerformanceReport>
schema = RuntimeSchema
.getSchema(PerformanceReport. class );
LinkedBuffer
buffer = LinkedBuffer.allocate( 4096 );
byte []
protostuff = null ;
try {
protostuff
= ProtostuffIOUtil.toByteArray(report, schema, buffer);
} catch (Exception
ex) {
ex.printStackTrace();
} finally {
buffer.clear();
}
return protostuff;
}
|
-
将byte数组写入文件
public void byteToFile( byte []
bytes, String filepath) {
FileOutputStream
fos = null ;
File
out = new File(filepath);
if (out.exists())
{
out.delete();
}
try {
out.createNewFile();
fos
= new FileOutputStream(filepath);
fos.write(bytes);
} catch (Exception
e) {
e.printStackTrace();
} finally {
if (fos
!= null )
{
try {
fos.close();
} catch (IOException
e) {
e.printStackTrace();
}
}
}
}
|
- 这样你就可以随意将运行中的java对象存储为文件了

-
同样修改后,调试,首先你先将序列化的文件读取出来
1
2
3
4
5
6
7
8
9
10
11
12
|
public byte []
fileToBytes(String filepath) {
Path
path = Paths.get(filepath);
byte []
data = null ;
try {
data
= Files.readAllBytes(path);
} catch (IOException
e) {
e.printStackTrace();
} finally {
return data;
}
}
|
-
将读取到byte数组反序列化为需要的java对象
public PerformanceReport
deserializeProtoStuffReport( byte []
bytesList) {
Schema<PerformanceReport>
schema = RuntimeSchema.getSchema(PerformanceReport. class );
PerformanceReport
product = new PerformanceReport();
ProtostuffIOUtil.mergeFrom(bytesList,product,schema);
return product;
}
|