首页 > 解决方案 > 如何访问序列化对象以从另一种方法更新其数据?

问题描述

我正在开发一个基本上允许用户创建、显示和编辑学生的项目。一旦创建了学生,就会自动分配一个 ID,然后将数据写入文件,以显示学生从文件中读取的对象。我使用 ObjectOutputStream 编写日期并使用 ObjectInputStream 从文件中读取数据,这工作正常,现在的想法是当用户输入 4 时,这是编辑学生的选项,程序会要求输入学生的 ID 号他们希望更新,我尝试先打开文件进行读取然后写入,我的想法是访问包含 ID 的学生变量,它位于CreateStudent()将用户输入的 ID 与写入文件但无法从 EditStudent() 访问学生变量及其数据的 ID 进行比较。有没有办法访问这些数据以便我可以比较它们?另外,有没有办法在访问 ID 后,只编辑与该 ID 相关的信息,而不是文件中的所有内容?我会很感激任何想法,这是我的代码:

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.*;
import java.lang.ClassNotFoundException;
public class MidTermProject  extends ObjectOutputStream {

    private boolean append;
    private boolean initialized;
    private DataOutputStream dout;
    static AtomicInteger idGenerator = new AtomicInteger(0001);
    static int id;
    
    protected MidTermProject(boolean append) throws IOException, SecurityException {
        super();
        this.append = append;
        this.initialized = true;
    }
    
    public MidTermProject(OutputStream out, boolean append) throws IOException {
        super(out);
        this.append = append;
        this.initialized = true;
        this.dout = new DataOutputStream(out);
        this.writeStreamHeader();
    }
    
    @Override
    protected void writeStreamHeader() throws IOException {
        if (!this.initialized || this.append) return;
        if (dout != null) {
            dout.writeShort(STREAM_MAGIC);
            dout.writeShort(STREAM_VERSION);
        }
    }
    
    public static int getId() {
        return id;
    }
    ///Create Student method
    public static void CreateStudent() throws IOException {
        String FullName;
        String address;
        String city;
        String state;
        File file = new File("StudentInfo.dat");
        boolean append = file.exists();
        
        Scanner keyboard = new Scanner(System.in);
        
        try (
                FileOutputStream fout = new FileOutputStream(file, append);
                MidTermProject oout = new MidTermProject(fout, append);
            ) {
            id = idGenerator.getAndIncrement();
            String student = Integer.toString(getId());
            oout.writeObject("Student ID: " + student);
            
            System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
            FullName = keyboard.nextLine();
            oout.writeObject("Full Name: " + FullName);
            
            System.out.print("Address: ");
            address = keyboard.nextLine();
            oout.writeObject("Address: " + address);
            
            System.out.print("City: ");
            city = keyboard.nextLine();
            oout.writeObject("City: " + city);
            
            System.out.print("State: ");
            state = keyboard.nextLine();
            oout.writeObject("State: " + state + "\n");
        
            oout.close();
            
            System.out.print("\nDone\n");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        
    }
    ///Edit Student method
    public static void EditStudent(String student) throws IOException {
        String editName;
        String editaddress;
        String editCity;
        String editState;
        int editID;
        String editStudent;
        boolean endOfFile = false;
        
        Scanner keyboard = new Scanner(System.in);
        
        System.out.print(student);
        
        System.out.print("Enter the ID of the student you would like to edit: ");
        editID = keyboard.nextInt();
        String editingID = Integer.toString(editID);
        
        FileInputStream fstream = new FileInputStream("StudentInfo.dat");
        ObjectInputStream inputFile = new ObjectInputStream(fstream);
        
        File file = new File("StudentInfo.dat");
        boolean append = file.exists();
        
        while(!endOfFile)
        {
            try
            {
                FileOutputStream fout = new FileOutputStream(file, append);
                MidTermProject oout = new MidTermProject(fout, append);
                editStudent = (String) inputFile.readObject();
                if(editingID == student) {
                    System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
                    editName = keyboard.nextLine();
                    oout.writeObject("Full Name: " + editName);
                        
                    System.out.print("Address: ");
                    editaddress = keyboard.nextLine();
                    oout.writeObject(editaddress);
                        
                    System.out.print("City: ");
                    editCity = keyboard.nextLine();
                    oout.writeObject(editCity);
                        
                    System.out.print("State: ");
                    editState = keyboard.nextLine();
                    oout.writeObject(editState);
                        
                    oout.close();
                        
                    System.out.print("Successfully Edited");
                } else {
                    System.out.print("Error");
                }
            }
            catch (EOFException | ClassNotFoundException e)
            {
                endOfFile = true;
            }
        }
    }
    ///Display Student method
    public static void DisplayStudent() throws IOException {
        FileInputStream fstream = new FileInputStream("StudentInfo.dat");
        ObjectInputStream inputFile = new ObjectInputStream(fstream);
        
        String student;
        boolean endOfFile = false;
        
        while(!endOfFile)
        {
            try
            {
                student = (String) inputFile.readObject();
                System.out.print(student + "\n");
            }
            catch (EOFException | ClassNotFoundException e)
            {
                endOfFile = true;
            }
        }
        System.out.println("\nDone");
        
        inputFile.close();
    }
    ///Main method
    public static void main(String[] args) throws IOException {
        
        int start = 0;
        
        while(start >= 0) {
            Scanner keyboard = new Scanner(System.in);
            
            System.out.println("Here is the sample of menu choices for Main Menu.");
            
            System.out.println("\nWelcome to University Enrollment" + "\n1. Create Student" +
                                "\n2. Create Course" + "\n3. Create Enrollment" + "\n4. Edit Student" + "\n5. Edit Course"
                                + "\n6. Edit Enrollment" + "\n7. Display Student" + "\n8. Display Course" + "\n9. Display Enrollment"
                                + "\n10. Grades Sub Menu" + "\n0. --- Quit ---");
            
            System.out.println("Please enter a valid choice(1-10, 0 to Quit) :");
            int userInput = keyboard.nextInt();
            
                if(userInput == 1) {
                    CreateStudent();
                } else if(userInput == 2) {
                    CreateCourse();
                } else if(userInput == 3) {
                    CreateEnrollment();
                } else if(userInput == 4 ) {
                    EditStudent(null);
                } else if(userInput == 5) {
                    EditCourse();
                } else if(userInput == 6) {
                    EditEnrollment();
                } else if(userInput == 7) {
                    DisplayStudent();
                } else if(userInput == 8) {
                    DisplayCourse();
                } else if(userInput == 9) {
                    DisplayEnrollment();
                } else if(userInput == 10) {
                    GradesSubMenu();
                } else if(userInput == 0) {
                    System.out.print("Done\n");
                } else {
                    while(userInput > 10) {
                        System.out.println("Invalid Option, Please try again.");
                        userInput = keyboard.nextInt();
                        if(userInput == 1) {
                            CreateStudent();
                        } else if(userInput == 2) {
                            CreateCourse();
                        } else if(userInput == 3) {
                            CreateEnrollment();
                        } else if(userInput == 4 ) {
                            EditStudent(student);
                        } else if(userInput == 5) {
                            EditCourse();
                        } else if(userInput == 6) {
                            EditEnrollment();
                        } else if(userInput == 7) {
                            DisplayStudent();
                        } else if(userInput == 8) {
                            DisplayCourse();
                        } else if(userInput == 9) {
                            DisplayEnrollment();
                        } else if(userInput == 10) {
                            GradesSubMenu();
                        } else if(userInput == 0) {
                            System.out.print("Done\n");
                        }
                    }
                }
           }
    }

标签: javaserializationdeserializationjava.util.scanner

解决方案


推荐阅读