我有一个客户端应用程序,它有 10 多个类,每个类都有 100 多个需要跟踪的组件。当程序运行时,用户输入数字,选择项目,切换复选框等。我需要想出一种方法来保存程序关闭时输入的所有数据,并具有在程序再次运行时抓取的能力上次运行的所有数据。
我已经研究过序列化,但我需要保存的一些内容不可序列化,因此不起作用。我还研究过 SingleFrameApplication 和 session 存储,但徒劳无功。
写入文件会导致需要数小时的乏味编码,而且可能效率低下。有谁知道我还能如何解决这个毛茸茸的问题?
更新:
按照@home的建议,我做了以下事情:
public Main() throws FileNotFoundException {
initComponents();
//read the file
Read();
//...
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
try {
//write to the file, the program is closing
Write();
} catch (FileNotFoundException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void Read() throws FileNotFoundException {
try{
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream("test.xml")));
//set the JTabbedPane to what is in the file
tab = (JTabbedPane) decoder.readObject();
decoder.close();
}catch(Exception e){
//there was no test.xml file so create one
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("test.xml")));
encoder.writeObject(null);
encoder.close();
}
}
private void Write() throws FileNotFoundException {
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("test.xml")));
//clear all previous things in the file
encoder.flush();
//write the JTabbedPane into the file
encoder.writeObject(tab);
encoder.close();
}
在这些更改之后,当我运行程序时弹出的所有内容都是一个空白的 JTabbedPane。谁能解释一下为什么会这样?
最佳答案
如果您只是想序列化与 JavaBeans 规范兼容的对象,请查看 XML 编码器和解码器:http://download.oracle.com/javase/6/docs/api/java/beans/XMLEncoder.html , http://download.oracle.com/javase/6/docs/api/java/beans/XMLDecoder.html
编辑:这里的教程:http://java.sun.com/products/jfc/tsc/articles/persistence4/
关于java - 保存大量动态用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6794755/