繁体   English   中英

使用ObjectOutputStream和ObjectInputStream从JTable打开/保存数据

[英]Open/Save data from JTable with ObjectOutputStream and ObjectInputStream

我有一个PhoneBook应用程序,它将数据从JTable存储到arraylist中。 在GUI中,我有“保存”和“打开”按钮,这些按钮假定将数据保存和打开为文件对象。 我设法创建了一个文件,其中包含来自arraylist的信息。

更新:如何不能使其将信息加载回JTable?

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

这是代码:

模型类中(扩展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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM