0

I need help with saving an array to a text file. So I have the following array

private Passenger[] queueArray = new Passenger[30];

and this is the class that I have

public class Passenger 
{

private String firstName;
private String surname;
private int secondsInQueue;

Passenger(String firstName, String surname)
{
    this.firstName = firstName;
    this.surname = surname;
    secondsInQueue = 0;
}

public String getName() 
{
    return firstName + " " + surname;
}

public void setName(String firstName, String surname) 
{
    this.firstName = firstName;
    this.surname = surname;
}

public Integer geSeconds() 
{
    return secondsInQueue;
}

public void setSecondsInQueue(Integer SecondsInQueue) 
{
    this.secondsInQueue = SecondsInQueue;
}

public void display() 
{
    System.out.println(firstName + " " + surname + " " + secondsInQueue);
}


}

I need to save the first name and the surname of the passengers to a text file. And then I need to read the file back to the array.

I am literally so stuck... Any help would be appreciated.

Thank You!

Softy
  • 5
  • 3
  • Have a look at the following serialization post https://stackoverflow.com/questions/17293991/how-to-write-and-read-java-serialized-objects-into-a-file – J11 Apr 08 '20 at 17:08

1 Answers1

0

Change the class implementation as below, to support java serialization. No methods to implement, it is a marker interface.

import java.io.*;
public class Passenger implements Serializable {}

Then you can write the objects in to any file with any extension. Then using java deserialization you can read the object array and iterate it through. Refer to this article, it has a simple example https://www.javatpoint.com/serialization-in-java.

At the time you de-serialize the object, you can call the getter method for the array object and iterate it through.

 ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  
    YourClass s=(YourClass)in.readObject(); 
    Passenger[] pasngrArray = s.getPassengerArray(); // call a method to get the array
    for (Passenger p : pasngrArray){
// your code to access the two properties here. 
}
Hisat
  • 43
  • 5