【发布时间】:2017-07-21 11:31:14
【问题描述】:
我一直在努力创建一个序列化方法来序列化我所有现有的对象。这就是我所做的:
我的班级:
public class Test implements Serializable{
ArrayList<TheOtherClass> obj = new ArrayList<>();
public static void main(String[] args) {
Test test = new Test();
test.addTest("This", "Is", "Some");
test.addTest("Text", "As", "Example");
test.saveAllArrays();
}
// omitted code down here.
public void addTest(String some, String random, String text) {
obj.add(new TheOtherClass(some, random, text));
}
public void saveTest(Object obj) throws IOException{
ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream("SaveFile.bin"));
save.writeObject(obj);
}
public void saveAllArrays(){
for(TheOtherClass all : obj){
try {
saveTest(all);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
我的对象类:
public class TheOtherClass implements Serializable{
private String some;
private String random;
private String savedText;
Getter 和 setter 方法被省略。
【问题讨论】:
-
这是真实代码中的其他内容,这只是一个示例,但感谢您的快速响应。
-
您的
addTest()声明和实现在哪里?另外,您的问题需要解释您遇到的问题。仅仅“挣扎”并不能告诉我们太多...... -
saveAllArrays()在哪里?而test test = new test();将不起作用,因为该类被称为Test。请只发布您尝试运行的实际代码,而不是一个到处都有问题的随机示例。另外,您应该告诉我们确切的问题是什么 - 错误?例外?输出错误? -
抱歉,我刚刚修复了它。希望现在一切都好。不幸的是,我不能把我的实际代码放上去,否则我的作品在上交时会被标记为抄袭。我遇到的问题是我不知道为什么它没有序列化。
-
@BhargavModi
Object不是 Java 中的保留字。
标签: java serialization arraylist