I'm working on a school assignment that is supposed to open a serialized file and output it. I can't figure out why it isn't printing anything. It doesn't seem like the loop is working at all. Any ideas?
public ReadFile()
{
try
{
fis = new FileInputStream("Clients.ser");
ois = new ObjectInputStream(fis);
}
catch(Exception e) {}
try
{
while(true)
{
//cast according to class Record
r = (Record) ois.readObject();
System.out.print(r.account + r.firstName + r.lastName + r.balance);
}
}
catch(IOException ioe) { ioe.printStackTrace(); }
catch(ClassNotFoundException cnfe) {}
}
Edit
Added a stacktrace to IOException and it returned:
Record; local class incompatible: stream classdesc serialVersionUID = 5124020354301486787, local class serialVersionUID = -8881068308941519505
ReadFile.java
Record.java
That message means that the class you are trying to deserialize is not the same as the class you specified.
Were you given the Record class by whoever serialized it, or did you write it yourself?
Related
I am performing a project, where so far in the discipline, we can not use database to persist the data. I am persisting the data in .tmp files. The first time I persisted the list of doctors, and it worked, but now that I'm trying to persist the patient user data, but this error happens, that file is not found.
These are my load, anda save methods in the class "SharedResources":
public void loadUserPatient(Context context) {
FileInputStream fis1;
try {
fis1 = context.openFileInput("patient.tmp");
ObjectInputStream ois = new
ObjectInputStream(fis1);
userPatient = (UserPatient) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
public void saveUserPatient(Context context) {
FileOutputStream fos1;
try {
fos1 = context.openFileOutput("patient.tmp",
Context.MODE_PRIVATE);
ObjectOutputStream oos =
new ObjectOutputStream(fos1);
oos.writeObject(userPatient);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
here is the whole class: https://ideone.com/f3c74u
the error is happening on line 16 of MainActivity:
SharedResources.getInstance().loadUserPatient(this);
here is the whole class "Main": https://ideone.com/OyiljP
And I think this error is ocurring because of the 52nd line of the UserPatientAdd class:
SharedResources.getInstance().getUserPatient();
because when I work with an ArrayList, I put an add at the end of the line, like:SharedResources.getInstance().getDoctors().add(doctor);
And I get confused on how to proceed when I deal only with a user.
This is the whole UserPatientAdd class: https://ideone.com/clUSa3
How can I solve this problem?
You need to set the UserPatient using something like this
In your SharedResources class, create a new method:
public void setUserPatient(UserPatient user) {
userPatient = user;
}
Then in your UserPatientAdd class set the new object:
UserPatient userPatient = new UserPatient (birth, name, bloodType, bloodPressure, cbpm, vacinesTaken, vacinesToBeTaken,
allergies,weight, height, surgeries, desease);
SharedResources.getInstance().setUserPatient(userPatient);
Done
I am trying to write an ArrayList of Question objects called questions to a file, then reading the file.
My problem is that when I am reading the file, it gives me an error that says: java.lang.ClassCastException: java.lang.String cannot be cast to Question at Quiz.load
My question is, why is this problem occurring and how can I fix it? I've been reading a lot of tutorials and they just cast the object to the class name which is what I did. I included my save & load functions.
Inside Quiz class:
Write Objects To File
ArrayList<Question> questions = new ArrayList<>();
//filename given by user
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(questions);
Read Objects From File
ArrayList<Question> readQuestions = new ArrayList<>();
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.print("QUIZ LOADING...");
readQuestions.add((Question)ois.readObject()); //problem occurs
Imagine that you have an empty box. You put an apple into the box.
Then you close it, and open it later on. Now, do you think it would work out to expect to find a hamburger in that box?
But that is what you are doing - storing a String and expecting to find a Question object. And that class cast exceptional is how the jvm tells you about reality not fitting your assumptions.
Solution: either store question objects - or expect strings to come back when reading the file.
You are serializing a list and deserializing it with Question.
Just change
readQuestions.add((Question) ois.readObject()); //problem occurs
with this
readQuestions = (ArrayList<Question>) ois.readObject();
Further explanation :
When i tried the example i got this error :
java.lang.ClassCastException: java.util.ArrayList cannot be cast to Question
So most likely if you are getting ClassCastException with String, you are also missing Serializable interface on Question. Something like this :
class Question implements Serializable {
String text;
public Question(String text) {
this.text = text;
}
}
Adding working code :
import java.io.*;
import java.util.ArrayList;
public class ObjectIS {
public static void main(String[] args) {
new ObjectIS().save();
new ObjectIS().load("abcd");
}
public void save() {
try {
ArrayList<Question> questions = new ArrayList<>();
questions.add(new Question("what is your name"));
//filename given by user
FileOutputStream fos = new FileOutputStream("abcd");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(questions);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void load(String filename) {
try {
ArrayList<Question> readQuestions = new ArrayList<>();
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.print("QUIZ LOADING...");
// readQuestions.add((Question) ois.readObject()); //problem occurs
readQuestions = (ArrayList<Question>) ois.readObject();
System.out.println("ois = " + readQuestions);
ois.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassCastException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
class Question implements Serializable {
String text;
public Question(String text) {
this.text = text;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Question{");
sb.append("text='").append(text).append('\'');
sb.append('}');
return sb.toString();
}
}
It is exactly as I said. You are serialising a String:
oos.writeObject(questions.toString());
And then attempting to deserialize it as a Question, which it never was:
(Question)in.readObject();
Solution:
remove the .toString() part.
deserialize as a List<Question>, which is what it really will be.
I got a problem with Serialization and Deserialization in java. In my program whenever I create a file then I also creating a fileInfo object and then I serializing in a secure_store.dat file and after deserializing from that file also.For example I can create test1.txt with a new fileInfo object and serialize that fileInfo object then i can create test2.txt with again different fileInfo object and serialize it also without a problem. Whenever i deserialize the secure_store.dat I can easily see that 2 objects but the problem is whenever i close the program and reopen the program and create test3.txt with a fileInfo object and try to serialize, it deletes the 2 old object in the secure_store.dat file and whenever I deserialize the file I can only see the last object the others always deleted(which are created before the program closes). How i can solve this problem and return the all three objects ? Below you can see my code...
public static void serialization(ArrayList<FileInfo> allFiles) {
try {
FileOutputStream fileOut = new FileOutputStream("secure_store.dat");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allFiles);
out.close();
fileOut.close();
} catch (IOException i) {
i.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public static ArrayList<FileInfo> deSerialization() throws FileNotFoundException {
ArrayList<FileInfo> arraylist = new ArrayList<FileInfo>();
try {
FileInputStream fileIn = new FileInputStream("secure_store.dat");
ObjectInputStream in = new ObjectInputStream(fileIn);
arraylist = (ArrayList<FileInfo>) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return arraylist;
} catch (ClassNotFoundException c) {
System.out.println("Class not found");
c.printStackTrace();
return arraylist;
}
return arraylist;
}
hi i'm learing Object Serialization and tried this
import java.io.*;
class Employee implements Serializable{
Employee(int temp_id,String temp_name)
{
id=temp_id;
name=temp_name;
}
int id;
String name;
}
public class SerialTest{
public static void main(String[] args)
{
Employee e1=new Employee(14,"John");
try{
FileOutputStream fileStream=new FileOutputStream("myserial.ser");
ObjectOutputStream os=new ObjectOutputStream(fileStream);
os.writeObject(e1);
}
catch(IOException ioex)
{
ioex.printStackTrace();
}
finally{
os.close();
}
}//main ends
}//class ends
The program worked before i put in the call to
os.close();
Now i doesn't compile , i get the error saying
SerialTest.java:29: cannot find symbol
symbol : variable os
location: class SerialTest
os.close();
^
It worked before i tried to close the ObjectOutPutStream ,
the contents of the serialized file are below ,
¬í^#^Esr^#^HEmployee^S<89>S§±<9b>éØ^B^#^BI^#^BidL^#^Dnamet^#^RLjava/lang/String;xp^#^#^#^Nt^#^GSainath
~
i cant seem to understand where i am going wrong , please help!
You want to use the purpose-built try-with-resources:
try (ObjectOutputStream os =
new ObjectOutputStream(new FileOutputStream("myserial.ser"));) {
os.writeObject(e1);
} catch(IOException ioex) {
ioex.printStackTrace();
}
Is it possible to save a loaded class to a file?
Class cc = Class.forName("projects.implementation.JBean");
Or, maybe to get the physical location of that class?
Yes you can as Class.class implements Serializable interface you can serialize it into file and as well deserialize again.
Example -
Class Test{
public static void main(String[] args) throws ClassNotFoundException {
try {
OutputStream file = new FileOutputStream("test.ser");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try {
Class cc = Class.forName("com.test.Test");
System.out.println(cc);
output.writeObject(cc);
} finally {
output.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
try {
// use buffering
InputStream file = new FileInputStream("test.ser");
InputStream buffer = new BufferedInputStream(file);
ObjectInput input = new ObjectInputStream(buffer);
try {
// deserialize the class
Class cc = (Class) input
.readObject();
// display
System.out.println("Recovered Class: " + cc);
} finally {
input.close();
}
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Serializing a Class object in Java serializes little more than the qualified name of the class. When deserializing the class is looked up by name.
In the general case, I don't think it's possible to get the bytes corresponding to a class definition (the bytecode) once it has been loaded. Java permits classes to be defined at runtime and, so far as I'm aware, doesn't expose the bytes after the class has been loaded.
However, depending on the ClassLoader in use, you may find that
cc.getResourceAsStream("JBean.class")
is all you need, loading the class stream as a resource using its own ClassLoader.
Another option could be to intercept the loading of the class. The ClassLoader will get to see the bytes in "defineClass", so a custom ClassLoader could store them somewhere.