java - 如何修复“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();
}
}
解决方案
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();
}
推荐阅读
- aws-application-load-balancer - 基于 ALB 入口控制器路径的路由
- django - 在子目录上部署 Django App (Namecheap)
- javascript - NextJs youtube iframe cookie
- primefaces - 有没有办法在不使用 JavaScript 的情况下在 primefaces 水平条形图中显示点标签?
- angular - 为什么我会收到“没有重载匹配此调用”错误
- python - 即使在关闭 gui 后 Python 也保存变量
- python - 我想使用python的replace()函数删除文本中的字符,但只删除了一半
- php - MySQL (PHP) 不根据 SQL 查询对 Array 进行排序
- spring-boot - 如何在 Spring、Jpa、Hibernate 中创建复合主键,其中一个复合键是另一个具有多对一连接的表的外键?
- java - 如何使用 xml 格式的 wsdl 生成类