Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

how to write and read student object from a binary files in java

I am writing a program to store some student object that user creates in a binary file. this program can also read data from that binary file created. i think there is a problem in writing that data to the binary file.

this is an example to store 2 students the program stores students alright but there is a problem reading that information (I don't know it might also be a problem while writing data). any suggestion to make the code better and run with no errors?

also is there any better ways to write this program to store as much students as user wants to and read that data and search it?? I mean to have some sort of search option and user can search for an specific student.

here is my code:

   import java.util.*;

public class write_object_to_binary_file {

    public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException, IOException {

        Scanner input = new Scanner(System.in);

        for (int i = 0; i < 2; i++) {

            System.out.println("Student first name: ");
            String fName = input.next();

            System.out.println("Student last name: ");
            String lName = input.next();

            System.out.println("Enter ID: ");
            int id = input.nextInt();

            System.out.println("Enter gpa: ");
            byte gpa = input.nextByte();

            writedata(fName, lName, id, gpa);
        }
        readData();

    }

    public static void writedata(String fName, String lName, int id, byte gpa) {

        student stu = new student();
        stu.first = fName;
        stu.last = lName;
        stu.id = id;
        stu.gpa = gpa;

        try {

            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            System.out.println("Writing information");
            oos.writeObject(stu);
            oos.close();
            System.out.println("Done");

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void readData() throws FileNotFoundException, IOException, ClassNotFoundException {

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
        for (int i = 0; i < 2; i++) {

            System.out.println("reading object");
            student stu = (student) ois.readObject();
            System.out.println(stu.first);
            System.out.println(stu.last);
            System.out.println(stu.id);
            System.out.println(stu.gpa);
            System.out.println("done reading object");

        }

        ois.close();
    }

}

class student implements Serializable {
    String first;
    String last;
    int id;
    byte gpa;
}```

question from:https://stackoverflow.com/questions/65875514/how-to-write-and-read-student-object-from-a-binary-files-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you write multiple objects with an ObjectOutputStream, it makes a block data record that stores the information about the objects. If at any point you then close the stream and later reopen it to write more objects, the block data record will be overwritten. Every time you call writedata this problem occurs. You also do not open the file in append mode, so it simply replaces the existing data, but this would still cause problems here.

But there is a better way that fixes this issue and will let you generalise your code to many students. Keep making your objects, and then store them all in a List, and just write the single List object to file. The serialization process will write all the members of the list to file too.

You should capitalise names of classes, but I will stick with your class name here:

    List<student> studentList = new ArrayList<>();

    for (int i = 0; i < n; ++i) {

        System.out.println("Student first name: ");
        String fName = input.next();

        System.out.println("Student last name: ");
        String lName = input.next();

        System.out.println("Enter ID: ");
        int id = input.nextInt();

        System.out.println("Enter gpa: ");
        byte gpa = input.nextByte();

        student stu = new student();
        //setting these fields with a constructor to would be better
        stu.first = fName;
        stu.last = lName;
        stu.id = id;
        stu.gpa = gpa;

        studentList.add(stu);
    }

    //this part is serializing the list and writing it to file
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
    System.out.println("Writing information");
    oos.writeObject(studentList);
    oos.close();
    System.out.println("Done");

    //this part deserializes the list from file, and then iterates over its members
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"));
    System.out.println("reading object");
    List<student> list = (List) ois.readObject();
    System.out.println("done reading object");
    for (student stu : list) {
        System.out.println(stu.first);
        System.out.println(stu.last);
        System.out.println(stu.id);
        System.out.println(stu.gpa);
    }

The code above will overwrite the existing file each time it is run, but I leave that to you. Your code may also have other issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...