I wanna make an ArrayList of Student and save it to a file for later use. I successfully wrote it but when I read it back to ArrayList, I have only one Object.
public class Student implements Serializable{
public String fname, lname, course;
int section;
private static final long serialVersionUID = 1L;
public static ArrayList<Student> students = getStudent();
public Student() {
}
public Student(String fname, String lname, String course, int section){
this.fname = fname;
this.lname = lname;
this.course = course;
this.section = section;
}
public static void addStudent(){
String fname = GetInput.getInput("Enter the First Name: ");
String lname = GetInput.getInput("Enter the Last Name: ");
String course = GetInput.getInput("Enter the Course: ");
String S_section = GetInput.getInput("Enter the section: ");
int section = Integer.parseInt(S_section);
Student student = new Student(fname, lname, course, section);
students.add(student);
System.out.println("Writing to file...");
try {
writeToFile(student);
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static ArrayList<Student> getStudent(){
try{
FileInputStream fis = new FileInputStream("C:\\students.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Student> students1 = (ArrayList<Student>) ois.readObject();
ois.close();
return students1;
} catch( ClassNotFoundException | IOException ex){
System.out.println(ex.getMessage());
return null;
}
}
public static void listStudent(ArrayList<Student> students){
System.out.println("View the Records in the Database:");
for(Student student: students){
System.out.println("Name: " + student.fname + " " + student.lname);
System.out.println("Course: " + student.course);
System.out.println("Section: " + student.section);
System.out.println();
}
}
static void writeToFile(Student student) throws FileNotFoundException, IOException{
String path = "C:\\students.ser";
FileOutputStream fos = new FileOutputStream(path, true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(student);
oos.close();
System.out.println("New Record has been written!");
}
When I read file by calling getStudent() and print it out by listStudent() I have only one record of the file.
Please help me!
Much appreciate.
EDIT
I had tried writing an arraylist to file and read it into arraylist. I'll show you how I did that.
Firstly, I write arraylist to file:
public static ArrayList<Student> students = new ArrayList<>();
public static void addStudent(){
Student student = new Student(fname, lname, course, section);
students.add(student);
System.out.println("Writing to file...");
try {
writeToFile(students);
}catch...
}
static void writeToFile(ArrayList<Student> students) throws FileNotFoundException, IOException{
String path = "C:\\students.ser";
FileOutputStream fos = new FileOutputStream(path, true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(students);
oos.close();
System.out.println("New Record has been written!");
And then I read student file:
public static ArrayList<Student> getStudent(){
try{
FileInputStream fis = new FileInputStream("C:\\students.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Student> students1 = (ArrayList<Student>) ois.readObject();
ois.close();
return students1;
} catch( ClassNotFoundException | IOException ex){
System.out.println(ex.getMessage());
return null;
}
}
I can see that in the file I have many objects as the file size keep growing. But I only one object after read it, which is my very first object I wrote to file.
I would suggest you update your Serialization code for your Student class (because you're not Serializing your static students) as follows -
// This controls how Student(s) will be written.
private void writeObject(ObjectOutputStream oos)
throws IOException {
oos.defaultWriteObject();
// How many students we're tracking.
oos.writeInt(students.size());
for (Student student : students) {
oos.writeObject(student);
}
System.out.println("session serialized");
}
// Control how we read in Student(s).
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
ois.defaultReadObject();
// how many Students to read.
int size = ois.readInt();
for (int i = 0; i < size; i++) {
Student s = (Student) ois.readObject();
students.add(s);
}
System.out.println("session deserialized");
}
You state in comment:
Thanks for your comment. I noticed that, however I appended the new object to the old file, so technically I have bunch of objects in my file. FileOutputStream fos = new FileOutputStream(path, true);
While this technically does append to the end of a file, and works great with text files, I really don't think that this will work or work well with serialization. I would guess that to append with serialization, you'd first have to read all the objects in from the file, and then write without appending all of them via the serialization mechanism. I would re-write your input and output code if I were you.
Edit
I fear that you've got too much disparate stuff all crammed into one single class, making for a messy and hard to debug program. Some general recommendations to help clean up this assignment:
First create a class called Student -- you've done this -- but make it a pure Student class with private first name, last name, section and course fields, getters and setters for those fields (you need these), appropriate constructors (I think you've got this).
Give it a decent public String toString() method that returns a String that holds the values of the object's fields.
Get everything else out of Student, all the static methods, all the ArrayLists, any code for writing to or reading from files.
Create another class, say called StudentCollection
Give it a private non-static ArrayList<Student> field, say called students.
Give it an addStudent(Student student) method that allows outside classes to add Student objects to this class.
Give it a public String toString() method that returns the list's toString(), i.e., return students.toString();.
Give it a public void readFromFile(File file) method that uses serialization to read an ArrayList<Student> from a File.
Give it a public void writeToFile(File file) method that uses serialization to write an ArrayList<Student> to a File.
Finally, create a TestStudent class that has only one method, a public static void main method.
In main, create a StudentCollection object.
Fill it with Students using your addStudent(...) method.
Create a File object and call writeToFile(...) passing in your File.
Then test reading from the same file...
For example, the main method could look almost like the code below. Note though that in my test case to prove that this works, I created a simplified Student class, one that only took 2 parameters, for first and last names. Your code obviously will take more parameters.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class StudentTest {
private static final String DATA_FILE_PATH = "myFile.dat";
public static void main(String[] args) {
Student[] students = {new Student("John", "Smith"),
new Student("Mike", "Barnes"),
new Student("Mickey", "Mouse"),
new Student("Donald", "Duck")};
// create our collection object
StudentCollection studentColl1 = new StudentCollection();
// print out that it currently is empty
System.out.println("studentColl1: " + studentColl1);
// Add Student objects to it
for (Student student : students) {
studentColl1.addStudent(student);
}
// show that it is now full
System.out.println("studentColl1: " + studentColl1);
// create a file
File myFile = new File(DATA_FILE_PATH);
// write out our collection to file on disk
studentColl1.writeToFile(myFile);
// create another collection object
StudentCollection studentColl2 = new StudentCollection();
// show that it is empty
System.out.println("studentColl2: " + studentColl2);
// read the list back into the new StudentCollection object
File myFile2 = new File(DATA_FILE_PATH);
studentColl2.readFromFile(myFile2);
// add a few more Student's:
studentColl2.addStudent(new Student("Stack", "Overflow"));
studentColl2.addStudent(new Student("Donald", "Trump"));
// show the result
System.out.println("studentColl2: " + studentColl2);
}
}
You're writing a single Student object:
oos.writeObject(student);
But are trying to get an ArrayList:
ArrayList<Student> students1 = (ArrayList<Student>) ois.readObject();
Related
I am working on a school project that basically allows the user to create, edit and display students. I have a createStudent() that writes the info into the file using Scanner and ObjectOutputStream. The displayStudent() reads the data from the file using ObjectInputStream and displays it. The idea with editStudent() is to ask the user to enter the ID of the student they want to edit and then change the date and write it back to the file, what I have been trying to do is read the data from the file using ObjectInputStream and then assign that data into ArrayList or HashMap, I think I will be using ArrayList because HashMap is unordered. When I try to add the data from the file into ArrayList I get the following error:
java.io.EOFException at java.base/java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:3231) at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1663) at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:519) at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:477) at MidTermProject.editStudent(MidTermProject.java:194) at MidTermProject.main(MidTermProject.java:381)
Here is my code for editStudent():
public static void editStudent() throws IOException {
int editID;
String student;
ArrayList<String> studentEdit = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
FileInputStream fstream = new FileInputStream("studentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
System.out.print("Enter the ID of the student you would like to edit: ");
editID = keyboard.nextInt();
try {
student = (String) inputFile.readObject();
studentEdit.add(student);
System.out.print(studentEdit);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
///Added create student method
public static void createStudent() throws IOException {
File file = new File("studentInfo.dat");
boolean append = file.exists();
Scanner keyboard = new Scanner(System.in);
try (
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
) {
id = idGenerator.getAndIncrement();
String convertedId = Integer.toString(getId());
oout.writeObject(convertedId);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
oout.writeObject(FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
oout.writeObject(address);
System.out.print("City: ");
city = keyboard.nextLine();
oout.writeObject(city);
System.out.print("State: ");
state = keyboard.nextLine();
oout.writeObject(state);
oout.close();
System.out.println("Done!\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is the class code for MidTermProject
public class MidTermProject extends ObjectOutputStream {
private boolean append;
private boolean initialized;
private DataOutputStream dout;
static AtomicInteger idGenerator = new AtomicInteger(0001);
static int id;
public static String FullName;
public static String address;
public static String city;
public static String state;
public static String className;
public static String instructor;
public static String department;
public static String classNumber;
public static String courseNumber;
public static String year;
public static String semester;
public static String grade;
public static String studentID;
public static String courseID;
public static String enrollmentID;
public static HashMap<String, Integer> map = new HashMap<>();
Scanner keyboard = new Scanner(System.in);
protected MidTermProject(boolean append) throws IOException, SecurityException {
super();
this.append = append;
this.initialized = true;
}
public MidTermProject(OutputStream out, boolean append) throws IOException {
super(out);
this.append = append;
this.initialized = true;
this.dout = new DataOutputStream(out);
this.writeStreamHeader();
}
#Override
protected void writeStreamHeader() throws IOException {
if (!this.initialized || this.append) return;
if (dout != null) {
dout.writeShort(STREAM_MAGIC);
dout.writeShort(STREAM_VERSION);
}
}
If think you are misusing serialization: whether Serialization is bad or good is another matter, but that should be something like that:
List<Student> students = ... ;
try (OuputStream os = Files.newOutputStream(Paths.get("out"));
ObjectOutputStream oos = new ObjectOutputStream(os)) {
oos.writeObject(students);
}
Reading it should be as simple as:
try (InputStream is = Files.newInputStream(Paths.get("out"));
ObjectInputStream iis = new ObjectInputStream(is)) {
List<Student> students = iis.readObject(students);
}
You must ensure that Student is Serializable and have only Serializable or transient fields:
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String fullName;
private String address;
private transient String wontBeExported;
...
}
Notice that the fields are not static: serialization is about serializing an object and its fields. Static fields are not part of any instance.
You should also not have to extends the ObjectOutputStream class, or if you do, you must ensure that you read the object written by your implementation of ObjectOutputStream is symmetric with the ObjectInputStream you are using:
If you write an header, your ObjectInputStream must read said header.
If you write an object, your ObjectInputStream must read said object.
And the order is important: you can't read the object before the header is read.
You should also read the Java tutorial: https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html
I need to store and read ArrayList Objects to a file, which that itself isn't the issue. I need to store it with a specific format and have it have a "header" of sorts while still having each ArrayList Object be usable from the file. Another part to it, is it needs to be readable by opening the text file itself, so no serialization can be used (Unless I'm just severely mistaken on how to use serialization). Example of how the working file should look below (Figure 1).
I will include all my code below just so nothing important isn't show on accident.
Airline.java
public class Airline extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Airline.fxml"));
Scene scene = new Scene(root);
stage.setTitle("Seat Reservation");
stage.setResizable(false);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
Passenger p1 = new Passenger(0001, "John Smith", "1A", "AA12");
Passenger p2 = new Passenger(0002, "Annah Smith", "1B", "AA12");
//creating arraylist
ArrayList <Passenger> pList = new ArrayList <Passenger>();
pList.add(p1);
pList.add(p2);
try {
FileOutputStream fos = new FileOutputStream(new
File("reservations.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(pList);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream(new
File("reservations.txt"));
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList list = (ArrayList) ois.readObject();
System.out.println(list.toString());
ois.close();
fis.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
launch(args);
}
}
Passenger.java
public class Passenger implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String seat;
private String flight;
Passenger() {
};
public Passenger (int idP, String nameP,String seatP, String flightP) {
this.id = idP;
this.name = nameP;
this.seat = seatP;
this.flight = flightP;
}
#Override
public String toString() {
return "\n" + id + " " + name + " " + seat + " " + flight;
}
}
The code I have currently shows this when opening the text file (Figure 2 below).
If anyone has any suggestions please let me know! I've been stumped for quite a while now.
Also, if this breaks any rules or doesn't have the proper tags, let me know and I'll remove/edit it.
In your example you use serialization (you can read more about it here Introduction to Java Serialization), which saves an object to a file in binary format. So basically you're saving the whole ArrayList, including its internal fields and values as an array of bytes.
But what you really need is simply writing to a text file.
Here's one of the ways you can do that using java.io.PrintWriter:
PrintWriter p = new PrintWriter("reservations.txt");
p.write("your text goes here");
And yes, you have to prepare the text for writing manually.
In your case the best approach would be overriding toString() method of Passenger class, so you can write to a file as simply as this:
Passenger p1 = new Passenger(0001, "John Smith", "1A", "AA12");
Passenger p2 = new Passenger(0002, "Annah Smith", "1B", "AA12");
p.write(p1.toString());
p.write(p2.toString());
toString() method has to concatenate required fields(ID, Name, SeatNumber, Flight#) and return them as a single String with a TAB character as a delimiter.
Please clear my understanding why I am getting of value of company after deserialization. I know "Statics are implicitly transient, so we don't need to declare them as such."
class Employee implements Serializable {
String name;
static String company = "My Company";
public Employee(String name) {
this.name = name;
}
}
public class Test8 {
public static void main(String[] args) throws Exception {
Employee e = new Employee("John");
serializeObject(e);// assume serialize works fine
Employee e1 = deserializeObject(); // assume deserialize works fine
System.out.println(e1.name + " " + e1.company);
}
public static void serializeObject(Employee e) throws IOException {
FileOutputStream fos = new FileOutputStream("Test8.cert");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
oos.flush();
oos.close();
}
public static Employee deserializeObject() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("Test8.cert");
ObjectInputStream oos = new ObjectInputStream(fis);
return (Employee) oos.readObject();
}
}
Value of static field company was set first time you used Employee class. In your case it would be in line:
Employee e = new Employee("John");
This value didn't change since it wasn't serialized and deserialized so it stayed the same, which means
System.out.println(e1.name + " " + e1.company);
prints John My Company.
But even if you remove lines
Employee e = new Employee("John");
serializeObject(e);
from your code, and invoke only
public static void main(String[] args) throws Exception {
Employee e1 = deserializeObject(); // assume deserialize works fine
System.out.println(e1.name + " " + e1.company);
}
Employee class will still be loaded inside deserializeObject (by oos.readObject() method) so its static fields will also be properly initialized to its default values.
I have succeeded in writing and reading a string to a file on my android app's internal storage, but I want to write an object and it's not working. I've read Oracle's documentation on the matter, which says for object fields to be transmitted over the stream the object needs to implement serializable, or something. I added imports serializable and implements serializable to the cat class but it threw an error. Without it "oos.writeObject(myCat);" causes an error too. I'm very confused.
The below code exists in a java activity class tied to a layout.xml. The user presses a button and the object is saved or loaded. As stated writing and reading a string seems to work fine, but objects less so.
private void writeFile()
{
try
{
String myFile = "myFile";
cat myCat = new cat("Harry", "blue", 11);
FileOutputStream fos = openFileOutput(myFile,MODE_WORLD_READABLE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myCat);
oos.close();
fos.close();
Toast.makeText(getBaseContext(),"object saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
And
private void readFile()
{
try
{
String myFile = "myFile";
FileInputStream fis = openFileInput(myFile);
ObjectInputStream ois = new ObjectInputStream(fis);
cat yourCat = (cat) ois.readObject();
ois.close();
fis.close();
String output = yourCat.name + " the " + yourCat.colour + " cat";
Toast.makeText(getBaseContext(),output,Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
}
}
The cat object
public class cat
{
public String name = "";
public String colour = "black";
public int age = 0;
public cat(String pName, String pColour, int pAge)
{
name = pName;
colour = pColour;
age = pAge;
}
}
Adding "implements Serializable" to the cat class works. I'm not sure why it didn't in the first place. Sorry for the fuss.
Try using:
MODE_PRIVATE
In the openFileOutput() method.
I have this arrayList in my UserArchive class, and a saveFile() method in my MainWindow class.
My problem is that every time I close the program all that shows in src/customerlist.txt is:
¨ÌsrUserArchiveYï≈ùÅ—ÀDLlisttLjava/util/ArrayList;xpsrjava.util.ArrayListxÅ“ô«aùIsizexpw
x.
Heres my code: Can anyone spot any problems?
public class UserArchive implements Serializable {
ArrayList<User> list = new ArrayList<User>();
public void regCustomer(User u) {
list.add(u);
}
public String toString() {
sorter();
String users = "";
Iterator<User> iterator = list.iterator();
while (iterator.hasNext()) {
users += iterator.next().toString() + "\n";
}
return users;
}
MainWindow class:
public class MainWindow extends JFrame {
private SaleWindow sW;
private UserArchive userA;
int customerID = 0;
////
public void saveFile() {
try {
FileOutputStream outStream = new FileOutputStream(
"src/customerlist.txt");
ObjectOutputStream utfil = new ObjectOutputStream(outStream);
utfil.writeObject(userA);
utfil.close();
} catch (NotSerializableException nse) {
JOptionPane
.showMessageDialog(this, "Objektet er ikke serialisert!");
} catch (IOException ioe) {
JOptionPane
.showMessageDialog(this, "Problem med utskrift til fil!");
}
}
Yes because ObjectOutputStream serializes objects in binary form. If you want serialize in some ASCII form try a JSON Serializer for example Jackson.
Please take a look at Javas serialization mechanismn. You're not writing the String content but the String objects (and the sourrounding list) in their binary form.
ObjectOutputStream is the wrong choice if all you want to do is write a plain text file. Take a closer look at java.io.FileWriter or java.io.PrintWriter.