final Marshaller marshaller = marshallerFactory.createMarshaller(configuration);
try(FileOutputStream os = new FileOutputStream(fileName)){
marshaller.start(Marshalling.createByteOutput(os));
marshaller.writeObject(obj);
marshaller.finish();
}
Exception in thread "main" java.io.NotSerializableException:
at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:274)
at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
接下来就是序列化的反向动作反序列化了。
代码很简单,我们直接上代码:
public void marshallingRead(String fileName) throws IOException, ClassNotFoundException {
// 使用river协议创建MarshallerFactory
MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("river");
// 创建配置文件
MarshallingConfiguration configuration = new MarshallingConfiguration();
// 使用版本号4
configuration.setVersion(4);
final Unmarshaller unmarshaller = marshallerFactory.createUnmarshaller(configuration);
try(FileInputStream is = new FileInputStream(fileName)){
unmarshaller.start(Marshalling.createByteInput(is));
Student student=(Student)unmarshaller.readObject();
log.info("student:{}",student);
unmarshaller.finish();
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
MarshallingReader reader= new MarshallingReader();
reader.marshallingRead("/tmp/marshall.txt");
}
运行上面的代码,我们可能得到下面的输出:
[main] INFO c.f.marshalling.MarshallingReader - student:Student(name=jack, age=18, className=first grade)