Java 使用文本字段在文件中存储学生数组列表
我制作了一个小型java swing应用程序,将学生列表存储在一个文件Java 使用文本字段在文件中存储学生数组列表,java,swing,arraylist,Java,Swing,Arraylist,我制作了一个小型java swing应用程序,将学生列表存储在一个文件students.txt中。 但我在将许多学生保存到文件中时遇到了一个问题: 当我点击“保存”按钮时,只存储一条学生记录。如果我在文本字段中输入新数据并再次单击“保存”按钮,则只保存新创建的学生,覆盖旧记录,同时我希望将新学生追加到文件中的现有学生列表中 这是我的密码: import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.
students.txt
中。
但我在将许多学生保存到文件中时遇到了一个问题:
当我点击“保存”按钮时,只存储一条学生记录。如果我在文本字段中输入新数据并再次单击“保存”按钮,则只保存新创建的学生,覆盖旧记录,同时我希望将新学生追加到文件中的现有学生列表中
这是我的密码:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class studentTest extends JFrame {
JPanel p1, p2, p3, p4, p5, p6;
JTextField f1, f2, f3, f4;
JLabel l1, l2, l3, l4;
JButton b1, b2, b3;
public studentTest() {
setBounds(100, 150, 300, 400);
b1 = new JButton("Save");
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
List<Student> Students = new ArrayList();
Student newStudents = new Student();
newStudents.setStudentFName(f1.getText());
newStudents.setStudentLName(f2.getText());
newStudents.setGPA(f4.getText());
newStudents.setID(f3.getText());
Students.add(newStudents);
try{
PrintWriter pw = new PrintWriter(new FileOutputStream("/Users/Yukki/Desktop/Students.txt"));
pw.println(newStudents+"\n");
pw.close();
} catch (FileNotFoundException ex) {
}
}
});
b2 = new JButton("First Record");
b3 = new JButton("Next");
l1 = new JLabel(" FirstName :");
l2 = new JLabel(" LastName :");
l3 = new JLabel(" ID :");
l4 = new JLabel(" GPA :");
f1 = new JTextField(10);
f2 = new JTextField(10);
f3 = new JTextField(10);
f4 = new JTextField(10);
p1 = new JPanel(new GridLayout(1, 2));
p1.add(l1);
p1.add(f1);
p2 = new JPanel(new GridLayout(1, 2));
p2.add(l2);
p2.add(f2);
p3 = new JPanel(new GridLayout(1, 2));
p3.add(l3);
p3.add(f3);
p4 = new JPanel(new GridLayout(1, 2));
p4.add(l4);
p4.add(f4);
p5 = new JPanel(new GridLayout(1, 1));
p5.add(b1);
p6 = new JPanel(new GridLayout(1, 2));
p6.add(b2);
p6.add(b3);
setLayout(new GridLayout(6, 1));
add(p1);
add(p2);
add(p3);
add(p4);
add(p5);
add(p6);
}
public static void main(String[] args) {
(new studentTest()).show();
}
}
导入java.awt.GridLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.ObjectOutputStream;
导入java.io.PrintWriter;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.Scanner;
导入java.util.StringTokenizer;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入javax.swing.JButton;
导入javax.swing.JFileChooser;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JPanel;
导入javax.swing.JTextField;
公共类学生测试扩展JFrame{
JPanel p1、p2、p3、p4、p5、p6;
JTextField f1、f2、f3、f4;
JLabel l1、l2、l3、l4;
按钮b1、b2、b3;
公立学生考试{
立根(100150300400);
b1=新按钮(“保存”);
b1.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
List Students=new ArrayList();
学生新闻学生=新学生();
newStudents.setStudentFName(f1.getText());
newStudents.setStudentLName(f2.getText());
setGPA(f4.getText());
setID(f3.getText());
学生。添加(新闻学生);
试一试{
PrintWriter pw=新的PrintWriter(新文件输出流(“/Users/Yukki/Desktop/Students.txt”);
pw.println(newStudents+“\n”);
关闭();
}捕获(FileNotFoundException ex){
}
}
});
b2=新的JButton(“第一条记录”);
b3=新的按钮(“下一步”);
l1=新的JLabel(“名字:”);
l2=新的JLabel(“姓氏:”);
l3=新的JLabel(“ID:”);
l4=新的JLabel(“GPA:”);
f1=新的JTextField(10);
f2=新的JTextField(10);
f3=新的JTextField(10);
f4=新的JTextField(10);
p1=新JPanel(新网格布局(1,2));
p1.添加(l1);
p1.添加(f1);
p2=新JPanel(新网格布局(1,2));
p2.添加(l2);
p2.添加(f2);
p3=新JPanel(新网格布局(1,2));
p3.添加(l3);
p3.添加(f3);
p4=新JPanel(新网格布局(1,2));
p4.添加(l4);
p4.添加(f4);
p5=新JPanel(新网格布局(1,1));
p5.添加(b1);
p6=新JPanel(新网格布局(1,2));
p6.添加(b2);
p6.添加(b3);
setLayout(新网格布局(6,1));
添加(p1);
添加(p2);
添加(p3);
增加(第4页);
添加(p5);
增加(第6页);
}
公共静态void main(字符串[]args){
(new studentTest()).show();
}
}
“newStudents”只是一个学生实例。迭代列表并编写每个项目。(列表名称应以简单的字母btw开头)。此外,您仅将一名学生添加到列表中
for (Student student: students) {
pw.println(student);
}
您可以重写student的toString(),以获得有意义的字符串表示形式。虽然有许多解决方案可以尝试,但我建议您使用。尝试使用,因为它将允许您定义将Student实例输出为XML的方法 这样,您就可以将多个实例添加到同一个文件中 可能会建议您序列化对象,但就我个人而言,我会避免这样做。它只打算用于物体的短期存储,通常用于通过电线传输,但这只是我的观点 使用示例更新… 这是基于和的示例 首先,我们需要定义
Student
类和JAXB注释。这使我们能够描述应该如何编组(转换)对象的实例
接下来,我们需要创建一个可以包含对象列表的简单包装器类。这是必需的,以便JAXB API可以更容易地访问内部数据
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType (XmlAccessType.FIELD)
@XmlRootElement
public class Students implements Iterable<Student> {
private List<Student> students;
public Students() {
this.students = new ArrayList<>(25);
}
public Student get(int index) {
return students.get(index);
}
public void add(Student student) {
students.add(student);
}
public void remove(Student student) {
students.remove(student);
}
public int size() {
return students.size();
}
@Override
public String toString() {
return "List-o-Students: " + size();
}
@Override
public Iterator<Student> iterator() {
return students.iterator();
}
}
哪个输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<students>
<students id="100">
<age>29</age>
<name>Bob</name>
</students>
<students id="101">
<age>19</age>
<name>John</name>
</students>
<students id="102">
<age>39</age>
<name>Joe</name>
</students>
<students id="103">
<age>25</age>
<name>Jane</name>
</students>
</students>
List-o-Students: 4
29
上下快速移动
19
约翰
39
乔
25
简
学生名单:4
使用可更新的示例更新
以下内容允许您在超时时动态更新XML。它的概念与读、写、读几乎相同,但提供了一些附加功能
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File xml = new File("file.xml");
Document document = db.parse(xml);
// Create a new context...
JAXBContext jc = JAXBContext.newInstance(Students.class);
// Create a new Binder from the context
Binder<Node> binder = jc.createBinder();
// Load the document
Students students = (Students) binder.unmarshal(document);
// Update the student at position 0
Student student = students.get(0);
student.setAge(100);
// Add a new student
students.add(new Student(200, "Harry", 65));
// Update the document
binder.updateXML(students);
// Write the contents back to the file..
FileOutputStream fos = null;
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
fos = new FileOutputStream(xml);
t.transform(new DOMSource(document), new StreamResult(fos));
} catch (TransformerFactoryConfigurationError | TransformerException exp) {
exp.printStackTrace();
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
} catch (ParserConfigurationException | SAXException | IOException | JAXBException exp) {
exp.printStackTrace();
}
试试看{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
File xml=新文件(“File.xml”);
Document=db.parse(xml);
//创建一个新的上下文。。。
JAXBContext jc=JAXBContext.newInstance(Students.class);
//从上下文创建新的活页夹
Binder Binder=jc.createBinder();
//加载文档
学生=(学生)活页夹.拆封(文件);
//更新位置0处的学生
学生=学生。获取(0);
学生设置(100);
//添加新学生
学生。加上(新学生(200,“哈里”,65));
//更新文档
binder.updateXML(学生);
//将内容写回文件。。
FileOutputStream=null;
试一试{
TransformerFactory tf=TransformerFactory.newInstance();
变压器t=tf.新变压器();
fos=新文件输出str
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<students>
<students id="100">
<age>29</age>
<name>Bob</name>
</students>
<students id="101">
<age>19</age>
<name>John</name>
</students>
<students id="102">
<age>39</age>
<name>Joe</name>
</students>
<students id="103">
<age>25</age>
<name>Jane</name>
</students>
</students>
List-o-Students: 4
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File xml = new File("file.xml");
Document document = db.parse(xml);
// Create a new context...
JAXBContext jc = JAXBContext.newInstance(Students.class);
// Create a new Binder from the context
Binder<Node> binder = jc.createBinder();
// Load the document
Students students = (Students) binder.unmarshal(document);
// Update the student at position 0
Student student = students.get(0);
student.setAge(100);
// Add a new student
students.add(new Student(200, "Harry", 65));
// Update the document
binder.updateXML(students);
// Write the contents back to the file..
FileOutputStream fos = null;
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
fos = new FileOutputStream(xml);
t.transform(new DOMSource(document), new StreamResult(fos));
} catch (TransformerFactoryConfigurationError | TransformerException exp) {
exp.printStackTrace();
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
} catch (ParserConfigurationException | SAXException | IOException | JAXBException exp) {
exp.printStackTrace();
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.bind.Binder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.jaxb.test.Student;
import org.jaxb.test.Students;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class JAXBExample {
public static void main(String[] args) {
Students students = new Students();
students.add(new Student(100, "Bob", 29));
students.add(new Student(101, "John", 19));
students.add(new Student(102, "Joe", 39));
students.add(new Student(103, "Jane", 25));
write(students);
students = null;
students = read();
for (Student student : students) {
System.out.println(student);
}
update();
students = null;
students = read();
for (Student student : students) {
System.out.println(student);
}
}
public static void write(Students students) {
System.out.println("----> Write");
try {
File file = new File("file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Students.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(students, file);
// jaxbMarshaller.marshal(students, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
public static Students read() {
System.out.println("----< Read");
Students students = null;
try {
File file = new File("file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Students.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
students = (Students) jaxbUnmarshaller.unmarshal(file);
System.out.println(students);
} catch (JAXBException e) {
e.printStackTrace();
}
return students;
}
public static void update() {
System.out.println("----> Update");
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File xml = new File("file.xml");
Document document = db.parse(xml);
JAXBContext jc = JAXBContext.newInstance(Students.class);
Binder<Node> binder = jc.createBinder();
Students students = (Students) binder.unmarshal(document);
Student student = students.get(0);
student.setAge(100);
students.add(new Student(200, "Harry", 65));
binder.updateXML(students);
FileOutputStream fos = null;
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
fos = new FileOutputStream(xml);
t.transform(new DOMSource(document), new StreamResult(fos));
} catch (TransformerFactoryConfigurationError | TransformerException exp) {
exp.printStackTrace();
} finally {
try {
fos.close();
} catch (Exception e) {
}
}
} catch (ParserConfigurationException | SAXException | IOException | JAXBException exp) {
exp.printStackTrace();
}
}
}