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.
Related
I'm trying to achieve the following...
I have an ArrayList of type class which stores class objects
each time it stores a new object I serialize it and wipe out the previous object.
I have methods like add search delete etc.
when I try to add I get then exception,
Exception Caught: java.io.NotSerializableException: java.io.BufferedReader
code:
public static ArrayList<Library> bookData = new ArrayList<Library>();
public void addBook()
{
objCount++;
try{
System.out.println("_________________Enter Book Details_________________");
System.out.println(" Enter title of the Book : ");
this.setBookTitle();
System.out.println(" Enter the Name of Author : ");
this.setBookAuthor();
System.out.println(" Enter the Subject of Book : ");
this.setBookSubject();
System.out.println(" Enter the Price of Book : ");
this.setBookPrice();
System.out.println(" Enter Number of Copies :");
this.setNoOfCopies();
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("Database.ser");
oos = new ObjectOutputStream(fos);
oos.flush();
oos.writeObject(bookData);
oos.close();
fos.close();
}catch(Exception e){
System.out.println("Exception Caught: "+e);
}
}catch(IOException e){
System.out.println("IO Exception Caught: "+e);
}catch(Exception e){
System.out.println("Exception Caught: "+e);
}finally{
try{
File file = new File("Books_Index.txt");
FileWriter fw = new FileWriter(file, true);
int count=getObjCount();
fw.write("\nBook Index ["+count+"] Contains Book Named: ["+getBookTitle()+"]");
fw.close();
//saveData();
}catch(Exception e){
System.out.println("Exception Caught: "+e);
}
}
}
Which, I googled and got the answer as you need to implement serializable interface.
I have already implemented it.
What could be the reason. I'm sending code by sharing my pastebin link
Link: https://pastebin.com/Q8F3iwex
Classes that implement Serializable interface can be serialized. InputStreamReader and BufferedReader don't implement this interface.
Quick Solution is that:
protected transient InputStreamReader inputStream = new InputStreamReader(System.in);
protected transient BufferedReader scan = new BufferedReader(inputStream);
it serializes objects in an object recursively when you serialize the object,Every object must be serializable.From the source code in jdk,object which is a String,Array,Enum or an implementation of Serializable can be serialized.
source code in ObjectOutputStream
// remaining cases
if (obj instanceof String) {
writeString((String) obj, unshared);
} else if (cl.isArray()) {
writeArray(obj, desc, unshared);
} else if (obj instanceof Enum) {
writeEnum((Enum<?>) obj, desc, unshared);
} else if (obj instanceof Serializable) {
writeOrdinaryObject(obj, desc, unshared);
} else {
if (extendedDebugInfo) {
throw new NotSerializableException(
cl.getName() + "\n" + debugInfoStack.toString());
} else {
throw new NotSerializableException(cl.getName());
}
}
In your Library class,there is a BufferedReader field,it can not be serialized.
you can try this
transient BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
Or implement your own serialization logic like this:
private void writeObject(ObjectOutputStream out) throws IOException {
//your own serialization logic
.......
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
//your own deserialization logic
........
}
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 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;
}
So I'm making a notepad application that logs date entered, a subject, and a body text field. When I hit my post button, everything appears properly in my ListView, but when I close the application and re-open it, only the date remains intact and the other two values are NULL. Below is the code I'm using.
public class LogList implements Serializable {
private String logDate;
private String logBody;
private String logSubject;
public LogList(String date, String LogBody, String LogSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
Back in my main class, I have my method that is supposed to save the three values into an ArrayList lts.
private void saveInFile(String subject_text, String date, String body_text ){
LogList lt = new LogList(date, subject_text, body_text);
lts.add(lt);
saveAllLogs();
}
Now if I change the order of the values in my new LogList, only the first one will be properly displayed after I close my app and reopen it. The following are my saveAllLogs method and my loadFromFile method.
private ArrayList<String> loadFromFile(){
ArrayList<String> logs = new ArrayList<String>();
try {
FileInputStream fis = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
while (true) {
LogList lt = (LogList) ois.readObject();
logs.add(lt.toString());
lts.add(lt);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
return logs;
}
private void saveAllLogs() {
try {
FileOutputStream fos = openFileOutput(FILENAME, 0);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (LogList lti : lts) {
oos.writeObject(lti);
}
fos.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
Any help would be greatly appreciated!
For one thing,
public LogList(String date, String LogBody, String LogSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
Seems wrong. As you have capitalized argument names, but you're setting the members with lowercase names.
Do you mean:
public LogList(String date, String logBody, String logSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
EDIT: Trivial thing, not impacting your code: You don't need your call to super() in your constructor as you're not extending any class.
The code below returns an IOException. Here's my main:
public class Main
{
public static void main(String[] args) {
Book b1 = new Book(100, "The Big Book of Top Gear 2010", "Top Gear",
"BBC Books", 120, "Book about cars.");
Book b2 = new Book(200, "The Da Vinci Code", "Dan Brown", "Vatican", 450,
"A fast paced thriller with riddles.");
Book b3 = new Book(300, "Le Petit Nicolas", "Sempe Goscinny", "Folio", 156,
"The adventures of petit Nicolas.");
ArrayList<Book> biblia = new ArrayList<Book>();
biblia.add(b1);
biblia.add(b2);
biblia.add(b3);
File f = new File("objects");
try {
FileInputStream fis = new FileInputStream("objects");
int u = fis.read();
if (u != -1) {
ObjectInputStream ois = new ObjectInputStream(fis);
Bookstore b = (Bookstore) ois.readObject();
ois.close();
} else {
Bookstore b = new Bookstore(biblia);
FileOutputStream fos = new FileOutputStream("objects");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(b);
oos.close();
}
} catch (FileNotFoundException ex1) {
System.out.println("File not found.");
} catch (IOException ex2) {
System.out.println("IO Error.");
} catch (ClassNotFoundException ex3) {
System.out.println("Class not found.");
}
}
This is the Bookstore class which I use just to store the ArrayList of Book objects in orded to use it in Object streams.
public class Bookstore implements Serializable {
private ArrayList<Book> myBooks = new ArrayList<Book>();
public Bookstore(ArrayList<Book> biblia) {
myBooks = biblia;
}
}
I've imported all the right libraries too.
What I try to do is: If the file is not empty, then read the ArrayList from there (the bookstore object that contains the arraylist). If it's empty write a new one.
The problem is that the only thing I get in returns is "IO Error." and I can't understand why.
It's wrong way to test if file exists. You are trying create stream from file which doesn't exists, and FileNotFoundException is thrown. Instead of:
FileInputStream fis = new FileInputStream("objects");
int u = fis.read();
if (u != -1) {
just use
if(f.exists()) { ... }
It would help you debug these problems if you printed the stack trace when you get an exception, but I am guessing that Book is not serializable.
Nightsorrow is probably right. To answer why you are getting "IO Error" out, it is because you told the program to print that if there was an IO Error. For the purposes of debugging your code I would delete the
catch (IOException ex2) {
System.out.println("IO Error.");
}
section of your code or comment it out so that you can get the stack trace. Then you can pinpoint where and why the error is occuring because it will give you an exception and what line that exception was thrown.