新对象不会出现在 javafx 中

new objects do not appear in javafx

我有一个学生数组列表,我正在用我的保存方法将它写入一个文本文件,每次我 运行 应用程序都会成功,它会在我第一次加载我的所有对象时 运行程序成功。我的问题是,当我关闭后再次启动应用程序并尝试保存和加载新对象时,它只从第一个会话加载我的旧对象,而不是任何新保存的 objects.Save 方法是写入和加载方法是阅读

package application;
import java.io.Serializable;
public class Student implements Serializable{
    
    
    private String name = null;     //students name
    private int ID = 0;             //students ID number
    private String DOB = null;      //Students Date of Birth
    
    
    public Student(String name,int ID, String DOB) {
        this.setName(name);
        this.setID(ID);
        this.setDOB(DOB);
    }
    
    public void printStudent() {
        System.out.println("Name: " + name + " ID: " + ID + " DOB: " + DOB);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getID() {
        return ID;
    }
    public void setID(int iD) {
        ID = iD;
    }
    public String getDOB() {
        return DOB;
    }
    public void setDOB(String dOB) {
        DOB = dOB;
    }
    @Override public String toString() {
        return "Name: " + name + "    | ID:  " + ID  + "    | Date of birth:  " + DOB;
    }
}

package application;
    
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
public class Test extends Application {
    
    
      ArrayList<Student> arraylist = new ArrayList<Student>();          //arraylist of student objects
      Student student;
      
      Student line;
      Validation validation = new Validation();
      
     
    
    @Override
    public void start(Stage primaryStage) {
        try {
        
            primaryStage.setTitle("MTU Student record system");
            
            
            
            Label enterNamelbl = new Label("Enter Student Name");
            TextField enterNametxt = new TextField();
            HBox hbox1 = new HBox(42,enterNamelbl,enterNametxt);
           
            hbox1.setAlignment(Pos.CENTER);
            
            Label enterIDlbl = new Label("Enter Student ID");
            TextField enterIDtxt = new TextField();
            HBox hbox2 = new HBox(70,enterIDlbl,enterIDtxt);
            hbox2.setAlignment(Pos.CENTER);
            
            Label enterDOBlbl = new Label("Enter Student Date of Birth");
            TextField enterDOBtxt = new TextField();
            HBox hbox3 = new HBox(27,enterDOBlbl,enterDOBtxt);
            hbox3.setAlignment(Pos.CENTER);
            
            Button addbtn = new Button("Add");
            Button removebtn = new Button("Remove");
            Button listbtn = new Button("List");
            HBox hbox4 = new HBox(12,addbtn,removebtn,listbtn);
            hbox4.setAlignment(Pos.CENTER);
            
            
            TextArea textArea = new TextArea();
            HBox hbox5 = new HBox(textArea);
            
            
           
            Button load = new Button("Load");
            Button save = new Button("Save");
            Button exit = new Button("Exit");
            HBox hbox6 = new HBox(12,load,save,exit);
            hbox6.setAlignment(Pos.BOTTOM_RIGHT);
            
           
            VBox vbox1 = new VBox(29,hbox1,hbox2,hbox3,hbox4,hbox5,hbox6);
            vbox1.setPadding(new Insets(10,10,10,10));
            
            
            //adding a student to the arraylist
            addbtn.setOnAction(e-> {
                
                validation.isInt(enterIDtxt, enterIDtxt.getText());
                String name = enterNametxt.getText();
                 int ID = Integer.parseInt(enterIDtxt.getText());
                 String Dob = enterDOBtxt.getText();
                 
                                        //validating user input
                Student student = new Student(name,ID,Dob);
                arraylist.add(student);
                System.out.println(arraylist);   //to remove later   
                 
                
            });
            
            //listing the arraylist of students
            listbtn.setOnAction(e -> {
                    textArea.setText(null);
                  for(Student stu : arraylist){
                      
                       textArea.appendText(stu + "\n");
                      
                      }
                
            });
            //removing a student
                removebtn.setOnAction(e -> {
                int ID = Integer.parseInt(enterIDtxt.getText());
                Student studentToRemove = null;         //temporary variable to store student obj   
                    for(Student student:arraylist){
                            if(student.getID()==ID);
                            studentToRemove = student;
                    }
                        if(studentToRemove==null)
                            System.out.println("No customer found");
                        else
                            arraylist.remove(studentToRemove);          //need to throw an alert here       
            });
            
                
            //saving everything to a txt file
                save.setOnAction(e ->{
                    
                    try {
                         File file  = new File("StudentData.txt");
                         //File to store student data
                         ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file,true));
                         os.writeObject(arraylist);         //writting all the items too the txt file
                         os.close();
                       }
                    
                    
                    catch(FileNotFoundException e1){
                    e1.printStackTrace();
                    }
                    catch(IOException e1) {
                        e1.printStackTrace();
                    }
                    
                });
                
           //load everything from the txt file
                load.setOnAction(e ->{
                    
                    try {
                        textArea.setText(null);
                        FileInputStream fis = new FileInputStream("StudentData.txt");
                        ObjectInputStream ois = new ObjectInputStream(fis);
                        List<Student> students = (List<Student>) ois.readObject();
            
                         // for(Student stu : students){
                              
                               textArea.appendText(students + "\n");
                              
                             // }
                        ois.close();
            
                    } 
                    catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    }
                    catch (IOException e1) {
                        e1.printStackTrace();
                    }
                                    
                    catch (ClassNotFoundException e1) {
                        e1.printStackTrace();
                    }
                        
                
                });
               
            
            Scene mainScene  = new Scene(vbox1,500,500);
            //mainScene.getStylesheets().add("application.css");
            primaryStage.setScene(mainScene);
            primaryStage.show();
            
            
        } catch(Exception e) {
            e.printStackTrace();
        }
        
        
    }
    
    public static void main(String[] args) {
        
        Application.launch(args);
        
    }
    
    
}

有2个问题

写作中

您正在指定

FileOutputStream(File,true)

docs 这会将数据附加到您的文件,因此您实际上并没有将数据添加到您的 ArrayList,但实际上它会将多个 ArrayList 附加到您的文件,因此删除布尔标志并写入

FileOutputStream(file);

这将覆盖文件的内容

阅读中

由于您的写入错误,您第一次只读取写入文件的第一个 ArrayList 运行 您的应用程序因此您只获取旧数据的原因

在加载 setAction 代码中从文件中读取 ArrayList 后,将加载的数据添加到应用程序使用的原始 ArrayList 中

arrayList.addAll(students);

写入文件的对象也不是文本格式,因此为了避免误导人们,为了清楚起见,将扩展名更改为其他内容