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!
in.readObject()returns a String, and you are casting toHashMap. That why you gotClassCastException. You may need write user details (user's field) in String format (may be comma separated values), then you can read them as a String, split with comma and assign them to user objects line by line.