【问题标题】:Not able to serialize java.util.HashMap object无法序列化 java.util.HashMap 对象
【发布时间】:2014-01-09 08:05:43
【问题描述】:

我正在尝试将 hashmap 写入文件并将其读回。最初,我的文件是空的。所以,当我尝试使用 readObject() 读取时,它会抛出 EOFException。我抓住了它并继续正常执行。然后,我输入了一个学生的详细信息。使用 rollnumber 作为键在 hashmap 中插入详细信息。然后,我使用 writeObject() 将 hashmap 写入文件。我检查了文件,里面写了一些东西。 我关闭程序并再次执行它。 这次它应该已经读取了我写的 hashmap。但是,相反,它会清除文件并仍然抛出 EOFException。 帮帮我..我该怎么做???

Student.java

package student;

public class Student implements java.io.Serializable {
    private String name;
    private int age;

    class Address implements java.io.Serializable{
        String house;
        String street;
        String city;
        String state;
        int pin;
        Address(String house,String street,String city,int pin,String state){
            this.house = new String(house);
            this.street = new String(street);
            this.city = new String(city);
            this.state = new String(state);
            this.pin = pin;
        }
    }
    private Address addr;
    private int rollnumber;
    private String courses[];

    public Student(String name,int age,String house,String street,String city,String state,int pin,int roll, String courses[]){
        this.name = new String(name);
        this.age = age;
        this.addr = new Address(house,street,city,pin,state);
        this.rollnumber = roll;
        this.courses = new String[4];
        System.arraycopy(courses, 0, this.courses, 0, 1);
        System.out.println("NEW STUDENT CREATED..");
    }

    public String toString(){
        String s = rollnumber +" "+name+" "+age+"\n";
        return s;
    }

    int getRollNumber(){
        return rollnumber;
    }

}

我已将 Student 类和内部类 Address 都设为可序列化。告诉我这里是否有任何问题。

StudentRunner.java

package student;
import java.io.*;
import java.util.*;

public class StudentRunner {
    public static void main(String [] args) throws java.io.IOException, ClassNotFoundException{
        String file = "student.txt";
        StudentProcessor sp = new StudentProcessor();
        FileOutputStream fout = new FileOutputStream(file);
        FileInputStream fin = new FileInputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(fout);
        ObjectInputStream in = new ObjectInputStream(fin);

        HashMap<Integer, Student> hm= new HashMap<Integer, Student>();
        Student stud=null;
        try{
        hm = (HashMap<Integer, Student>)in.readObject();

                ///////// TROUBLE IN THE ABOVE LINE ///////////


        }catch(EOFException eof){
            System.out.println("sfdasfasfas");
        }

        Scanner scanner = new Scanner(System.in);
        int option=0;

        do{
            System.out.println("(1) Add User Details");
            System.out.println("(2) Display User Details");
            System.out.println("(3) Delete User Details");
            System.out.println("(4) Save User Details");
            System.out.println("(5) Exit");
            try{
                option = scanner.nextInt();
            }catch(InputMismatchException ime){
                System.out.println("Error!!! provide valid option(1-5).");
                continue;
            }


        switch(option){
            case 1:
                try{

                    scanner.nextLine();

                    System.out.println("Enter full name: ");
                    String name = scanner.nextLine();
                    System.out.println("Enter age: ");
                    int age = scanner.nextInt();
                    System.out.println("Enter rollnumber: ");
                    int rollnumber = scanner.nextInt();

                    scanner.nextLine();

                    System.out.println("Enter Address:");
                    System.out.println("  Enter house number ");
                    String house_num = scanner.nextLine();
                    System.out.println("  Enter street: ");
                    String street = scanner.nextLine();
                    System.out.println("  Enter city: ");
                    String city = scanner.nextLine();
                    System.out.println("  Enter state: ");
                    String state = scanner.nextLine();
                    System.out.println("  Enter pin: ");
                    int pin = scanner.nextInt();

                    String courses[] = new String[4];
                    System.out.println("Enter four courses(A-F)");
                    System.out.println("  Enter first course: ");
                    courses[0] = scanner.next();
                    System.out.println("  Enter second course: ");
                    courses[1] = scanner.next();
                    System.out.println("  Enter third course: ");
                    courses[2] = scanner.next();
                    System.out.println("  Enter fourth course: ");
                    courses[3] = scanner.next();

                    boolean flag = Validator.validateStudent(name, age, rollnumber, house_num, street, city, 
                                                             state, pin, courses);

                    stud= new Student(name,age,house_num,street,city,state,pin,rollnumber,courses);
                    if(flag){
                        hm.put(rollnumber, stud );
                    }
                }catch(InputMismatchException ime){
                    System.out.println("Error!!! Provide numeric value..");
                    continue;
                }
                break;
            case 2:
                Set set = hm.entrySet();
                Iterator itr = set.iterator();
                while(itr.hasNext()){
                    Map.Entry<Integer, Student> m =(Map.Entry<Integer, Student>) itr.next();
                    System.out.println(m.getValue());
                }
                break;
            case 3:
                break;
            case 4:
                out.writeObject(hm);
                break;
            case 5:
                break;
            default:
                System.out.println("Error!!! provide valid option(1-5).");
                continue;
        }

        if(option>=5)
            break;

        }while(true);
    }
}

StudentRunner.java 中的

hm.readObject() 是我阅读内容的地方。但它会清除已经写入的内容并抛出 EOFException。

【问题讨论】:

  • 这可能不是你的问题,但不要试图一次打开同一个文件多次;结果充其量是不可预测的。相反,在您需要文件之前打开它,读取或写入,然后关闭。
  • YES.. 问题不在于读取文件。可能是因为我同时打开了同一个文件进行读写。当我第一次读取文件然后关闭处理程序时问题消失了。并在我需要的地方打开文件进行写入,并在写入后关闭处理程序。

标签: java serialization input hashmap


【解决方案1】:

请记住始终在您用于编写的OutputStream 上调用close 方法。公认的做法是在 finally {} 块内执行此操作,这样您就可以完全确保您正在关闭 OutputStream(从而实际上将缓冲区刷新到磁盘中)

【讨论】:

  • 在 Java 7+ 中,推荐的方法是使用 try() { },其中 是涉及打开资源的变量定义,例如创建 I/O溪流。然后,您不必使用 finally { } 来显式关闭资源。此外,finally { } 中的 close() 可能会抛出一个 IOException,如果它被抛出,这反过来可能会隐藏 try { } 块中的原始异常。另请注意,在输出流的情况下,close() 会刷新流,这可能会导致额外的写入操作,因此您不能简单地忽略异常。
猜你喜欢
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 2016-07-30
  • 2014-08-04
  • 2015-05-29
  • 2016-03-04
相关资源
最近更新 更多