Reputation: 49
I'm trying to read the serialized data from a .dat file into its corresponding java class file. My .readObject() method keeps throwing ClassNotFoundException though. Why cant it read the data from the file? I'm trying to read it into a student class who's constructor accepts objects of its type then assigns the values of that object's variables to its variables.
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);
}
}
}
Here's the stack trace:
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)
Upvotes: 0
Views: 864
Reputation: 310909
Your Student
class is in a different package from what is expected. If you print the exception message that came with the ClassNotFoundException
you will see what the expected package was.
And an error creating an ObjectInputStream
or FileInputStream
is not necessarily an 'error reading from file'. Don't make up your own error messages. Use the one that comes with the exception. Even when you have the right message, as with ClassNotFoundException
, you're missing the actual class name that wasn't found, which was in the exception message. Don't do this.
Upvotes: 1