gpt4 book ai didi

java - 使用 ObjectOutputStream 和 ObjectInputStream 打开/保存 JTable 中的数据

转载 作者:太空宇宙 更新时间:2023-11-04 14:45:16 25 4
gpt4 key购买 nike

我有一个电话簿应用程序,它将数据从 JTable 存储到数组列表中。在 GUI 中,我有“保存”和“打开”按钮,它们可以将数据作为文件对象保存和打开。我已成功创建一个包含数组列表中的信息的文件。

更新:如何无法将信息加载回 JTable?

我是 Java 新手,感谢您的耐心和帮助。期待感谢!

代码如下:

model类中(扩展AbstractTableModel)

public void saveContact() throws FileNotFoundException, IOException {
f.createNewFile();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(listaContacte); // listaContacte is the arraylist
System.out.println("S-a salvat");
}

public void loadContact() throws IOException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
try {
ois.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(CarteDeTelefon.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("s-a incarcat ");
}
}

GUI

   private void saveActionPerformed(java.awt.event.ActionEvent evt) {                                     
try {
model.saveContact();
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void openActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fc = new JFileChooser();
if (evt.getSource() == open) {
int returnVal = fc.showOpenDialog(GUI.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
model.loadContact();
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);}
}
}
}

更新:

public void loadContact() throws IOException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
try {
List<Abonat> obiect = (List<Abonat>) ois.readObject(); // "variable `obiect` is not used"
} catch (ClassNotFoundException ex) {
Logger.getLogger(CarteDeTelefon.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("s-a incarcat ");

}

最佳答案

这没有任何用处:

ois.readObject();

并且相当于此代码:

3 + 5;

是的,这是有效的 Java,但是您没有对结果进行任何操作就丢弃了结果。对于我的简单示例,我会将加法的结果分配给 int 变量:

int result = 3 + 5;
// now I can print out the result, or use it elsewhere.

对于您的代码,您需要将读入的内容分配给变量,并且该变量需要与 listaContacte 变量的类型相同。您还需要将从该方法返回的结果转换为该类型。

SomeType someVar = (SomeType) ois.readObject; // catch relevant exceptions
// here create my new table model with someVar.

关于java - 使用 ObjectOutputStream 和 ObjectInputStream 打开/保存 JTable 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24469383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com