java - 序列化包含数据集的对象
问题描述
我正在使用带有 Java 的 Spark 2.3.1 我有一个封装数据集的对象。我希望能够序列化和反序列化这个对象。
我的代码如下:
public class MyClass implements Serializable {
private static final long serialVersionUID = -189012460301698744L;
public Dataset<Row> dataset;
public MyClass(final Dataset<Row> dataset) {
this.dataset = dataset;
}
/**
* Save the current instance of MyClass into a file as a serialized object.
*/
public void save(final String filepath, final String filename) throws Exception{
File file = new File(filepath);
file.mkdirs();
file = new File(filepath+"/"+filename);
try (final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
oos.writeObject(this);
}
}
/**
* Create a new MyClass from a serialized MyClass object
*/
public static MyClass load(final String filepath) throws Exception{
final File file = new File(filepath);
final MyClass myclass;
try (final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
myclass = ((MyClass) ois.readObject());
}
System.out.println("test 1 : "+ myclass);
System.out.println("test 2 : "+ myclass.dataset);
myclass.dataset.printSchema();
return myclass;
}
// Some other functions
}
但是序列化似乎没有正确完成。load() 函数给了我以下显示:
test 1 : MyClass@520e6089
test 2 : Invalid tree; null:
null
并在 printSchema() 上抛出 java.lang.NullPointerException
我缺少什么来正确序列化我的对象?
解决方案
SparkDatasets
仅在用于创建这些的会话范围内才有意义。因此,序列化Dataset
是完全没有意义的。
- 如果要序列化数据,只需写入
Dataset
持久存储。 - 如果您想“序列化”管道,只需继续使用采用某种形式输入并返回所需的代码(方法)
Dataset
。不要尝试序列化Dataset
自身。
推荐阅读
- node.js - 如何在 Express.js 中为每条路由存储一个变量?
- events - Dynamics CRM FetchXml 报表执行时触发的插件消息是什么
- scala - 当类型被擦除时,隐式如何找到使用泛型调用的正确方法?
- php - 如何在正则表达式中使用“或”?
- excel - 如何在公式中引用集合
- sql - 连接后操作员太慢的地方
- python - 为什么在安装 eli5 时出现 EnvironmentNotWritableError
- javascript - 从 tinymce 发布数据时,它不使用 Codeigniter 存储数据库
- node.js - 在 Heroku 上 WaitForSelector 超时
- javascript - cloudflare js worker 允许国家列表并阻止其余国家