I would really appreciate if anyone can help me with this issue. I'm getting an error when I run this class UniqueUsersData.java
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.HashSet
at gettingData.UniqueUsersData.main(UniqueUsersData.java:30)
UniqueUsersData.java:
package gettingData;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.io.Serializable;
import de.umass.lastfm.User;
public class UniqueUsersData {
public static void main(String[] args) throws IOException, ClassNotFoundException{
HashSet<User> userData = null;
String fileName = "users.csv";
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
try{
while(in != null ){ // keep reading if there are more lines in the file
userData = (HashSet<User>) in.readObject();
}
}catch(IOException e){
e.printStackTrace();
}
String file = "usersInfo.csv";
BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
for(User u: userData){
System.out.println(u.getId() + "," + u.getName() + "\n");
}
out.close();
} // end main method
} // end class
I have another class which gets the data using the last.fm api, stores User objects to an arraylist and then writes those objects to a file (users.csv). That all works fine, and I write to the file using an ObjectOutputStream
.
I've read things about the class needing to be Serializable
, but I'm assuming that de.umass.lastfm.User
doesn't implement it.
Is there something I'm missing here?
Thanks for any help!
You are getting an exception since data in file users.csv is stored as string whereas you are trying to convert (cast) it to HashSet . In general readObject() method returns an Object which can be casted to same data type which was serialized. Please check what object was added to file users.csv. Was it the ArrayList or something else.
Note: User objects cannot be stored in file if it is not Serializable, you would get java.io.NotSerializableException
Code below shows the sample User read and writes with some modification
User.java
UniqueUsersData.java