我编写了用于通过GeoTools读取和显示GIS形状文件的程序,并且我想保存程序的状态。
Main class.java
Project myproject=new Project();
myproject.mapLayers=this.frame.getMapContext().getLayers();
Project.java
import org.geotools.map.MapLayer;
public class Project implements Serializable{
public String name;
public MapLayer[] mapLayers;
public void save(String projectname){
ReadWriteObject.writeObject(projectname+".gpr",this);
}
public Project load(String projectname){
return (Project)ReadWriteObject.readObject(projectname);
}
}
ReadWriteObject
public class ReadWriteObject {
public static boolean writeObject(String filename, Object obj){
try {
FileOutputStream f = new FileOutputStream(new File(filename));
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
o.writeObject(obj);
o.close();
f.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
return false;
} catch (IOException e) {
System.out.println("Error initializing stream");
return false;
}
return true;
}
}
发生错误DefaultMapLayer
不是Serializable
。如何在Java中保存程序状态?
我只是简单地以某种格式(XML,JSON)写出进入地图的图层,样式,然后再次读回以重新创建地图。您实际上不需要存储程序的entire状态。
或者,您可以将propose a change添加到源代码中以将Serialize
添加到类中。理想情况下,您应该找到所有需要序列化且当前未实现Serialize
的必要类,并提交单个pull请求。