简体   繁体   中英

How to write an array of objects to a File in Java?

Suppose I have an object of class Student , which has the following fields:

String name;

int age;

int roll_number;

And I instantiate like so:

Student A[] = new Student();

Now, is there a way to store all this information in a text file using File Handling?

I thought about looping through each element in the array and then converting all the fields into Strings but that seems wrong.

Another way would be to use Serialization . Your Student class would have to implement Serializable :

class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    private String name;
    private int age;
    private int rollNumber;
    //...
}

Then to read and write the Student array:

try {
    Student[] students = new Student[3];

    //Write Student array to file.
    FileOutputStream fos = new FileOutputStream("students.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(students);
    oos.close();

    //Read Student array from file.
    FileInputStream fis = new FileInputStream("students.ser");
    ObjectInputStream ois = new ObjectInputStream(fis);
    Student[] studentsFromSavedFile = (Student[]) ois.readObject();
    ois.close();
}
catch (FileNotFoundException e) {
    e.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}
catch (ClassNotFoundException e) {
    e.printStackTrace();
}

You can always work out the format in your toString() method of the class so that when you do write to a file, it will write the object as per that format.

So lets say your toString() is,

public String toString() {
    return "Name : " + name + " : Age : " + age;
}

So this will write to your file as, (if you call bw.write(person.toString()); )

Name : Azhar : Age : 25

If you don't care of any format (text or binary), you can try a few ways:

  1. Serialize them using Jackson to JSON or XML
  2. Serialize then using Xstream to XML

Then you can store them to file using FileWriter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM