gpt4 book ai didi

java - 从 GUI java 将对象的属性写入文件时出错

转载 作者:行者123 更新时间:2023-11-30 03:47:43 25 4
gpt4 key购买 nike

我的 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

代码能够从文件中读取数据,但是一旦我尝试从数组列表中添加更多人,它就行不通了,有人可以帮助我吗?

最佳答案

But if i wanted to add more person objects to the file, the data in the file is overriden and the file will be empty.

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

pWriter = new PrintWriter(f1);
<小时/>

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

FileWriter fileWriter = new FileWriter(f1, true);
^--------- Append Mode

pWriter = new PrintWriter(fileWriter, true);
^----------- Auto Flush

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

使用 Java 7- The try-with-resources Statement 小心处理资源或finally 阻止。

关于java - 从 GUI java 将对象的属性写入文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25211718/

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