我对 Java 了解不多。我正在尝试读取一个文件,其中包含一个 int 和一个名为“Automobile”的类的各种实例。但是,当我反序列化它时,程序会抛出 ClassNotFoundException,我似乎不明白为什么。
代码如下:
try {
FileInputStream fin = new FileInputStream(inputFile);
ObjectInputStream input = new ObjectInputStream(fin);
conto = input.readInt();
Automobile[] macchine = new Automobile[conto];
for(int i = 0; i < conto; i++) {
macchine[i] = (Automobile)input.readObject();
}
String targa;
System.out.print("\nInserire le cifre di una targa per rintracciare l'automobile: ");
targa = sc1.nextLine();
for(int i = 0; i < conto; i++) {
if(macchine[i].getTarga().equals(targa))
System.out.println(macchine[i]);
}
} catch(IOException e) {
System.out.println("Errore nella lettura del file "+inputFile);
} catch(java.lang.ClassNotFoundException e) {
System.out.println("Class not found");
}
提前致谢。
编辑:这里是堆栈跟踪
java.lang.ClassNotFoundException: es4.Automobile
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:604)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1575)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1732)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at es4p2.Main.main(Main.java:35)
最佳答案
当你反序列化一个序列化的对象树时,所有对象的类都必须在类路径中。在此上下文中,ClassNotFoundException
很可能意味着所需的类之一不在类路径中。您必须解决此问题才能使反序列化工作。
在这种情况下,es4.Automobile
丢失了。
Could the problem be caused by a custom exception I made which is fired by Automobile?
我能想到的唯一其他可能性是:
es4.Automobile
对缺少的某些其他类有直接或间接的依赖es4.Automobile
或依赖类的静态初始化引发了类内部未捕获的异常。
但是(我认为)这两个应该导致不同的堆栈跟踪。
I just noticed the package name is es4p2, not es4. Why does it say es4? Could it be because the program which saves the file uses another package name?
我不知道为什么它们不同。您需要与编写代码/生成序列化对象的人交谈。但是,这很可能是您遇到问题的原因。具有不同包名的类是不同的类。期间。
当捕获到意外异常时,您应该始终输出(或更好地记录)堆栈跟踪。这将告诉您(和我们)更多关于出了什么问题,在本例中是缺少的类的名称。
关于java - 反序列化二进制类文件的内容时出现 ClassNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6300076/