我在Java中对对象的序列化和反序列化有问题,我认为这是因为我不太了解它是如何工作的。我的程序由Excel中的一些电子表格组成,但通过控制台。我有一类“书”和一类“页”。在Book中,我声明了Page的HashMap,在Page中声明了String的Hashmap(用于模拟单元格)。现在,我希望该书具有持久性,为此,我要序列化“ libro”对象(Book实例):
try {
FileOutputStream fileOut =
new FileOutputStream("H:\\Users\\thero\\Desktop\\bin\\libro.bin");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(libro);
out.close();
fileOut.close();
System.out.printf("Se ha guardado el libro correctamente");
}
catch (IOException i) {
i.printStackTrace();
}
此代码包含在我从主体调用的名为“ Salvar”的类的方法中。同时,我有一个带有相反方法的“ Cargar”类:
try {
FileInputStream fileIn = new FileInputStream("H:\\Users\\thero\\Desktop\\bin\\libro.bin");
ObjectInputStream in = new ObjectInputStream(fileIn);
libro = (Book) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Cargar.class.getName()).log(Level.SEVERE, null, ex);
}
我也从主要位置调用此方法,并且在执行该方法时不会发生异常跳转。但是,似乎它仅加载Book实例,但不加载Hashmap属性,因此,它不加载带有单元格的已创建电子表格。问题出在哪里?这是我班的上书代码:
package javacalc.items;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Book implements Serializable{
private HashMap<String, Page> libro;
private Page activePage;
private String nameActivePage;
public Book(){
this.libro = new HashMap<>();
}
public List <String> getListPages() {
ArrayList <String> myList = new ArrayList<>();
for (String s: this.libro.keySet())
myList.add(s);
return myList;
}
public void setListPages(String s, Page p) {
this.libro.put(s,p);
}
public void deletePage(String s){
this.libro.remove(s);
}
public Page getActivePage() {
return activePage;
}
public boolean setActivePage(String activePage) {
Page p = this.libro.get(activePage);
this.nameActivePage = activePage;
this.activePage = p;
return true;
}
public String getNameActivePage(){
return nameActivePage;
}
public boolean containsPage(String s){
return libro.containsKey(s);
}
public HashMap<String, Page> getLibro() {
return this.libro;
}
}
谢谢。
Okey,我认为我已经解决了,我只是在“ Cargar”中做了一些更改:
try {
String ruta = comando.substring(8, comando.length()-1).trim();
FileInputStream fileIn = new FileInputStream(ruta);
ObjectInputStream in = new ObjectInputStream(fileIn);
Book libro_c = (Book) in.readObject();
libro.setLibro(libro_c.getLibro());
in.close();
fileIn.close();
现在可以了!谢谢您的帮助!