【问题标题】:Error Writing Object's Attributes to File from GUI java从 GUI java 将对象的属性写入文件时出错
【发布时间】:2023-03-14 02:27:02
【问题描述】:

我的 GUI 代码有一个问题,我无法理解它,它涉及使用 GUI 框架编写文件。

您在下面的代码中看到,我可以使用JTable 添加、删除和显示人员对象。我遇到的问题是将每个对象的每个属性写入一个名为“PersonList.txt”的文件。

令人讨厌的是,假设我手动将值放入文件中,我的代码能够读取每一行并使用文件中的值创建人员对象。但是如果我想向文件中添加更多人对象,文件中的数据将被覆盖,文件将为空。

我的代码如下。

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

public class GUIstoringObjects extends JFrame implements ActionListener{

private JFrame frame;
private JButton button1, button2, button3, button4, button5, button6;
private JTextField box1, box2, box3;
private JLabel label1, label2, label3;
private JTable table;
private ArrayList<Person> pList = new ArrayList<Person>();
private ArrayList<Object[]> list;
private File f1, f2;
private PrintWriter pWriter;
private Scanner pReader;

public static void main(String[] args) throws FileNotFoundException{
    // TODO Auto-generated method stub
    GUIstoringObjects gui = new GUIstoringObjects();
    gui.frame.setVisible(true);
}

public GUIstoringObjects()
{
    initialize();
}

public void initialize()
{
    frame = new JFrame("Adding and Saving Person Objects");
    frame.setBounds(75,75,813,408);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    label1 = new JLabel("First Name:");
    label1.setBounds(32,27,60,25);
    frame.getContentPane().add(label1);

    label2 = new JLabel("Last Name:");
    label2.setBounds(264,27,82,25);
    frame.getContentPane().add(label2);

    label3 = new JLabel("Phone Number:");
    label3.setBounds(504,27,89,25);
    frame.getContentPane().add(label3);

    box1 = new JTextField();
    box1.setBounds(102,26,140,27);
    frame.getContentPane().add(box1);

    box2 = new JTextField();
    box2.setBounds(354,26,140,27);
    frame.getContentPane().add(box2);

    box3 = new JTextField();
    box3.setBounds(599,26,140,27);
    frame.getContentPane().add(box3);

    button1 = new JButton("Add Person");
    button1.addActionListener(this);
    button1.setBounds(120,76,122,33);
    frame.getContentPane().add(button1);

    button2 = new JButton("Remove Person");
    button2.addActionListener(this);
    button2.setBounds(120,121,122,33);
    frame.getContentPane().add(button2);

    button3 = new JButton("Display Person List");
    button3.addActionListener(this);
    button3.setBounds(252,76,154,33);
    frame.getContentPane().add(button3);

    button4 = new JButton("Save Person List");
    button4.addActionListener(this);
    button4.setBounds(416,76,154,33);
    frame.getContentPane().add(button4);

    button5 = new JButton("Load Person List");
    button5.addActionListener(this);
    button5.setBounds(416,121,154,33);
    frame.getContentPane().add(button5);

    button6 = new JButton("Quit Program");
    button6.addActionListener(this);
    button6.setBounds(599,76,140,33);
    frame.getContentPane().add(button6);

    table = new JTable();
    table.setBounds(0,176,797,194);
    frame.getContentPane().add(table);
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    String action = (((JButton) e.getSource()).getActionCommand());

    if(action.equals("Add Person"))
    {
        String fName = box1.getText();
        String lName = box2.getText();
        String pNo = box3.getText();

        Person p = new Person(fName,lName,pNo);
        pList.add(p);
        JOptionPane.showMessageDialog(null, fName+" has been Added!");
        box1.setText("");
        box2.setText("");
        box3.setText("");
    }
    if(action.equals("Remove Person"))
    {
        String nameChecker = box1.getText();
        for(int i = 0; i<pList.size(); i++)
        {
            if(nameChecker.equals(pList.get(i).getFName()))
            {
                pList.remove(i);
                JOptionPane.showMessageDialog(null, nameChecker+" has been deleted!");
            }
        }
    }
    if(action.equals("Display Person List"))
    {
        list = new ArrayList<Object[]>();
        for (int i = 0; i < pList.size(); i++) {
            list.add(new Object[] { 
            pList.get(i).getFName(), 
            pList.get(i).getLName(),
            pList.get(i).getPNo() 
          });
        }
        table.setModel(new DefaultTableModel(list.toArray(new Object[][] {}), 
                            new String[] {"First Name", "Surname", "Phone Number"}));
    }
    if(action.equals("Save Person List"))
    {
        f1 = new File("PersonList.txt");
        try {
            pWriter = new PrintWriter(f1);
            for(Person p: pList)
            {
                pWriter.println(p.getFName());
                pWriter.println(p.getLName());
                pWriter.println(p.getPNo());
            }
            JOptionPane.showMessageDialog(null, "Person List Stored in File 'PersonList.txt'");

        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    if(action.equals("Load Person List"))
    {
        f2 = new File("PersonList.txt");
        try {
            pReader = new Scanner(f2);
            while (pReader.hasNext())
            {
                String fName = pReader.nextLine();
                String lName = pReader.nextLine();
                String pNo = pReader.nextLine();

                Person p = new Person(fName,lName,pNo);
                pList.add(p);
            }
            JOptionPane.showMessageDialog(null, "Person List Loaded from 'PersonList.txt'");
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    if(action.equals("Quit Program"))
    {
        System.exit(0);
    }
}
}

这是我下面的人对象

public class Person {
   private String fName, lName, pNo;

public Person(String fName, String lName, String pNo)
{
    setFName(fName);
    setLName(lName);
    setPNo(pNo);
}

public void setFName(String fName)
{
    this.fName = fName;
}

public void setLName(String lName)
{
    this.lName = lName;
}

public void setPNo(String pNo)
{
    this.pNo = pNo;
}

public String getFName()
{
    return fName;
}

public String getLName()
{
    return lName;
}

public String getPNo()
{
    return pNo;
}

public String toString()
{
    return getFName()+" "+getLName()+" "+getPNo();
}

public void print()
{
    System.out.println(toString());
}
}

正如我上面已经说过的,为了争论,我们有

Bill
Gates
088491038
Cristiano
Ronaldo
0048103874

代码可以从文件中读取,但是一旦我尝试从数组列表中添加更多人,它就无法正常工作,有人可以帮助我吗?

【问题讨论】:

    标签: java swing file jtable awt


    【解决方案1】:

    但如果我想向文件中添加更多人对象,文件中的数据将被覆盖,文件将为空。

    每当您创建PrintWriter 的对象时,它都会清除现有文件的数据。

    pWriter = new PrintWriter(f1);
    

    您应该使用FileWriterappend mode 属性将数据附加到现有文件中。

    FileWriter fileWriter = new FileWriter(f1, true);
                                                 ^--------- Append Mode
    
    pWriter  = new PrintWriter(fileWriter, true);
                                             ^----------- Auto Flush
    

    您应该在完成所有读/写操作后关闭流。最好使用PrintWriterauto flush属性,避免手动调用flush()方法。

    使用Java 7- The try-with-resources Statementfinally 块小心处理资源。

    【讨论】:

    • 它修复了我在文件中没有任何内容的错误,但另一件事是它会导致重复,例如,如果我保存到文件,然后添加一个新的 Person 对象,然后再次保存,我会有重复,这可以避免吗?
    • “这可以避免吗?” 这是一个完全不同的问题。如果它有助于解决这个问题,请accept回答。
    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多