无法用Java从二进制文件中读取对象

时间:2015-09-17 00:10:04

标签: java serialization binary deserialization file-processing

我正在尝试将.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)

1 个答案:

答案 0 :(得分:1)

您的Student课程与预期不同。如果您打印ClassNotFoundException附带的异常消息,您将看到预期的包是什么。

创建ObjectInputStreamFileInputStream时出错并不一定是'从文件中读取错误'。不要编写自己的错误消息。使用异常附带的那个。即使你有正确的消息,就像ClassNotFoundException一样,你也错过了在异常消息中找不到的实际类名。不要这样做。