Sau khi viết mã bên dưới, tôi phải sử dụng các phương thức ghi đè tùy chỉnh readObject() và writeObject() trong StudentData để đọc và ghi các biến của đối tượng. Không sử dụng các phương thức defaultWriteObject hoặc defaultReadObject để làm điều này.Serialization - readObject writeObject ghi đè
Vấn đề là tôi không hiểu đầy đủ những gì đang được yêu cầu làm. Tôi đã đọc Uses of readObject/writeObject in Serialization nhưng tôi không thể có được đầu của tôi xung quanh nó.Có ai đó chỉ cho tôi đi đúng hướng?
Mã của tôi:
import java.io.*; //importing input-output files
class Student implements java.io.Serializable {
String name; // declaration of variables
String DOB;
int id;
Student(String naam, int idno, String dob) // Initialising variables to user
// data
{
name = naam;
id = idno;
DOB = dob;
}
public String toString() {
return name + "\t" + id + "\t" + DOB + "\t";
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
class StudentData //main class
{
public static void main(String args[]) throws IOException //exception handling
{
System.out.println("Enter the numbers of students:");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
Student[] students = new Student[n];
//Student[] S=new Student[n]; // array of objects declared and defined
for (int i = 0; i < students.length; i++) {
System.out.println("Enter the Details of Student no: " + (i + 1)); //reading data form the user
System.out.println("Name: ");
String naam = in.readLine();
System.out.println("ID no: ");
int idno = Integer.parseInt(in.readLine());
System.out.println("DOB: ");
String dob = (in.readLine());
students[i] = new Student(naam, idno, dob);
File studentFile = new File("StudentData.txt");
try {
FileOutputStream fileOutput = new FileOutputStream(studentFile);
ObjectOutputStream objectOutput = new ObjectOutputStream(fileOutput);
objectOutput.writeObject(students);
students = null;
FileInputStream fileInput = new FileInputStream(studentFile);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInput);
students = (Student[]) objectInputStream.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
for (Student student : students) {
System.out.println(student);
}
}
}
}
Sắp xếp lạ. Bạn đang * giả sử * gọi defaultWriteObject() và defaultReadObject(). – EJP