首页 > 解决方案 > 如何修复“ClassNotFoundException”?

问题描述

我正在尝试将 Doctor 类的对象读写到文件中。我不断收到这个“ClassNotFoundException”,它阻止我编译代码。

我尝试在其他文件上使用相同的方法,这似乎工作得很好。

我在Vector existing_v = (Vector)aois.readObject();行收到编译错误

    package com.example.docapp;

    import java.io.*;
    import java.util.*;

    public class Admin implements Serializable {

       public void addDoctor(Doctor D) throws Exception {
          String url = "com\\example\\docapp\\doctorslist.txt";
          File f = new File(url);

          FileOutputStream afos = new FileOutputStream(f);
          ObjectOutputStream aoos = new ObjectOutputStream(afos);

          if(!f.exists()) { // If file doesnt exist creating and insert a new vector
             Vector<Doctor> v = new Vector<Doctor>();
             v.add(D);
             aoos.writeObject(v);
          }
          else { // Extract the existing vector and add the object to it
             FileInputStream afis = new FileInputStream(f);
             ObjectInputStream aois = new ObjectInputStream(afis);
             Vector<Doctor> existing_v = (Vector<Doctor>)aois.readObject();

             existing_v.add(D);
             aoos.writeObject(existing_v);
             aois.close();
             afis.close();
          }

          System.out.println("\n\nSuccessfully added " + D.name);

          aoos.close();
          afos.close();
       }
    }

标签: javaobjectclassnotfoundexception

解决方案


Admin 类实际上不需要可序列化。你需要让Doctor类实现Serializable

此外,当您初始化时FileOutputStream,如果文件不存在,它将创建文件。之后,!f.exists()将永远不会评估为 true,并且会打乱您读取对象的尝试。

public void addDoctor(Doctor D) throws Exception {
    String url = "com\\example\\docapp\\doctorslist.txt";
    File f = new File(url);

    FileOutputStream afos;
    ObjectOutputStream aoos;

    if (!f.exists()) { // If file doesnt exist creating and insert a new vector
        afos = new FileOutputStream(f);
        aoos = new ObjectOutputStream(afos);
        Vector<Doctor> v = new Vector<Doctor>();
        v.add(D);
        aoos.writeObject(v);
    } else { // Extract the existing vector and add the object to it
        FileInputStream afis = new FileInputStream(f);
        ObjectInputStream aois = new ObjectInputStream(afis);
        Vector<Doctor> existing_v = (Vector<Doctor>) aois.readObject();

        existing_v.add(D);

        afos = new FileOutputStream(f);
        aoos = new ObjectOutputStream(afos);
        aoos.writeObject(existing_v);
        aois.close();
        afis.close();
    }

    System.out.println("\n\nSuccessfully added " + D.name);

    aoos.close();
    afos.close();
}

推荐阅读