Reputation: 119
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.
Upvotes: 1
Views: 14898
Reputation: 2286
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();
}
Upvotes: 3
Reputation: 3460
If you don't care of any format (text or binary), you can try a few ways:
Then you can store them to file using FileWriter
Upvotes: 0
Reputation: 365
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
Upvotes: 0