简体   繁体   English

如何从 java 中的二进制文件写入和读取学生 object

[英]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.我正在编写一个程序来存储用户在二进制文件中创建的一些学生 object。 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).这是一个存储 2 个学生的示例,该程序可以很好地存储学生,但是读取该信息时出现问题(我不知道在写入数据时也可能出现问题)。 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;
}```

When you write multiple objects with an ObjectOutputStream , it makes a block data record that stores the information about the objects.当您使用ObjectOutputStream编写多个对象时,它会创建一个块数据记录来存储有关对象的信息。 If at any point you then close the stream and later reopen it to write more objects, the block data record will be overwritten.如果您在任何时候关闭 stream 并稍后重新打开它以写入更多对象,则块数据记录将被覆盖。 Every time you call writedata this problem occurs.每次调用writedata时都会出现此问题。 You also do not open the file in append mode, so it simply replaces the existing data, but this would still cause problems here.您也没有在 append 模式下打开文件,因此它只是替换现有数据,但这仍然会导致问题。

But there is a better way that fixes this issue and will let you generalise your code to many students .但是有一种更好的方法可以解决这个问题,并且可以让您将您的代码推广到许多students Keep making your objects, and then store them all in a List , and just write the single List object to file.继续制作您的对象,然后将它们全部存储在List中,然后将单个List object 写入文件。 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:您应该大写类的名称,但我会在这里坚持使用您的 class 名称:

    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.您的代码可能还有其他问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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