I want the method to append a new person object according to the form each time the save button is clicked, and read the new content of the file each time the retrieve button is clicked, unfortunately it only reads the last entered person.
am now here for help
package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.io.*;
import java.net.URL;
import java.time.LocalDate;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private Button save, retrieve;
@FXML
private TextField first, last;
@FXML
private Label saved, retrieved;
@FXML
private DatePicker date;
@Override
public void initialize(URL location, ResourceBundle resources) {
//System.out.println(date.getValue());
save.setOnAction(e->{
savePerson();
});
retrieve.setOnAction(e->{
retrievePeople();
});
}
public void savePerson() {
if (first.getText().isEmpty() || last.getText().isEmpty()) {
saved.setText("Please enter all fields");
} else {
String firstName = first.getText().trim();
String lastName = last.getText().trim();
LocalDate birthDate = date.getValue();
try {
//create new instance of the newClass.
Person person = new Person(firstName, lastName, birthDate);
//write object to the file.
FileOutputStream fos = new FileOutputStream("file.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.flush();
oos.close();
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
saved.setText("NEw person saved");
}
}
public void retrievePeople(){
try{
boolean eof = true;
//read the saved objects from the file
FileInputStream fis = new FileInputStream("file.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
while(eof){
Person result = (Person) ois.readObject();
System.out.println(result.getFirstName() + " " + result.getLastName() + " " + result.getDateOfBirth());
eof = false;
}ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
retrieved.setText("Data retrieved");
}
}