我正在尝试将 .dat 文件中的序列化数据读取到其相应的 java 类文件中。但我的 .readObject() 方法不断抛出 ClassNotFoundException 。为什么无法从文件中读取数据?我试图将其读入一个学生类,该学生类的构造函数接受其类型的对象,然后将该对象的变量的值分配给其变量。
public class StudentTest
{
private static ObjectInputStream OIS;
public static void main(String[] args)
{
openFile();
readFile();
closeFile();
}
public static void openFile()
{
try
{
OIS=new ObjectInputStream(Files.newInputStream(Paths.get("C:\\Users\\Joey\\Desktop\\students.dat")));
}
catch(IOException e)
{
System.out.println("Error trying to read file. TERMINATING.");
System.exit(1);
}
}
public static void readFile()
{
try
{
while(true)
{
Student student=new Student((Student)OIS.readObject());
System.out.printf("%s", student.toString());
}
}
catch(ClassNotFoundException e)
{
System.out.println("Class not found. Terminating.");
System.exit(1);
}
catch(EOFException e)
{
System.out.println("End of file reached.");
}
catch(IOException e)
{
System.out.println("Error reading from file. TERMINATING.");
System.exit(1);
}
}
public static void closeFile()
{
try
{
if(OIS!=null)
OIS.close();
}
catch(IOException e)
{
System.out.println("IOEXCEPTION.");
System.exit(1);
}
}
}
这是堆栈跟踪:
java.lang.ClassNotFoundException: files.Student
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at java.io.ObjectInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at studentfiles.StudentTest.readFile(StudentTest.java:40)
at studentfiles.StudentTest.main(StudentTest.java:16)
最佳答案
您的 Student
类与预期的包位于不同的包中。如果您打印 ClassNotFoundException
附带的异常消息,您将看到预期的包是什么。
创建 ObjectInputStream
或 FileInputStream
时发生的错误不一定是“从文件读取错误”。不要自己编造错误消息。使用异常(exception)附带的那个。即使您有正确的消息(如 ClassNotFoundException
),您也会丢失未找到的实际类名称,该名称位于异常消息中。不要这样做。
关于java - 在 Java 中从二进制文件读取对象时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32620686/