Java ClassCastException while using FileInputStream - java

I am trying to save/load instances of my TicketSet class in Java. Below is the class and the class variables. The Ticket and Variable class are also Serializable.
public class TicketSet implements Serializable{
public final int setID;
public int ticketNum;
public Ticket[] tickets;
private static int xCount[];
private static int yCount[];
private static int zCount[];
private Variable x;
private Variable y;
private Variable z;
In another class I save an instance of the TicketSet class which seems to work fine. In the code, gen is just an instance of a controller class which initialises TicketSet.
TicketSet set;
if (f.exists()) {
FileOutputStream fileOut =new FileOutputStream(f,true);
AppendingObjectOutputStream out = new AppendingObjectOutputStream(fileOut);
set = gen.getTSet();
out.writeObject(set);
out.close();
fileOut.close();
} else {
FileOutputStream fileOut =new FileOutputStream(f,true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
set = gen.getTSet();
out.writeObject(set);
out.close();
fileOut.close();
}
To load the instances of TicketSet, I have the following code which throws the error.
ArrayList<Integer> tickid = new ArrayList<Integer>();
tSets = new HashMap<Integer, TicketSet>();
FileInputStream fileStr = null;
ObjectInputStream reader = null;
try {
fileStr = new FileInputStream("TicketSets.ser");
reader = new ObjectInputStream(fileStr);
System.out.println(fileStr.available());
TicketSet tSet= null;
while (fileStr.available()>0) {
Object next = reader.readObject(); //ERROR HERE
if (next instanceof TicketSet) {
tSet = (TicketSet) next;
System.out.println("ID: "+tSet.setID);
tSets.put(tSet.setID, tSet);
tickid.add(tSet.setID);
} else {
System.out.println("Unexpected object type: " + next.getClass().getName());
}
}
//System.out.println("Size: "+tSets.size());
reader.close();
fileStr.close();
}
catch(IOException i) {
i.printStackTrace();
}
catch (ClassNotFoundException c) {
System.out.println("TicketSet class not found");
c.printStackTrace();
}
The error thrown is:
ID: 7325825
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.io.ObjectStreamClass
So what I understand is:
The first TicketSet is loaded fine... which has ID=73225825
It is then trying to load an integer from the file rather than a TicketSet object.
Why is it trying to load an integer? Is there a way to skip reading anything other than objects? Should I try an alternative approach?

I was missing the Reset() in my AppendingObjectOutputStream.
ClassCastException when Appending Object OutputStream

Related

EOFException when I extract the Object Input/Out put Stream

I use ObjectInput/Output to initialize the hashmap named temp and it put all entry of the hashmap called map that is initialized to new and then use OutputStream to save it in file formatting is .ser
this work perfectly...
import java.io.*;
import java.util.HashMap;
public class PlayerInfo implements Serializable {
ObjectOutputStream out;
ObjectInputStream in;
File userData =new File("path.ser");
HashMap map ;
HashMap temp;
private Integer ID;
String name ;
boolean isItNull =false;
public static void main(String[] args) {
new PlayerInfo();
}
PlayerInfo(){
try {
initializeHashMap();
}catch (Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
private void initializeHashMap(){
try {
//initialize ObjectInputStream in same method when I use it and close it then
in =new ObjectInputStream(new FileInputStream(userData));
if (isItNull){
temp =new HashMap<Integer,PlayerInfo>();
}else {
map =new HashMap<Integer,PlayerInfo>();
temp = (HashMap<Integer, PlayerInfo>) in.readObject();
in.close();
}
}catch (Exception e){
isItNull =true;
initializeHashMap();
}
}
private void getInfo(){
System.out.println("Ok we are in get info so write your ID:-");
int id = 10;
}
#SuppressWarnings("unchecked")
private void createInfo()throws IOException{
//same here initialize ObjectOutputStreamin same method when I use it and close it then
out =new ObjectOutputStream(new FileOutputStream(userData));
System.out.println("Ok we are in create info so write your ID:-");
ID =10;
String scnS ="Mohammed";
System.out.println("Write your name");
map.put(ID,new PlayerInfo(scnS));
temp.putAll(map);
System.out.println("Saving....");
out.writeObject(temp);
out.close();
}
public PlayerInfo(String name){
this.name =name;
}
}
but this throw EFOException
import java.io.*;
import java.util.HashMap;
public class PlayerInfo implements Serializable {
ObjectOutputStream out;
ObjectInputStream in;
File userData =new File("path.ser");
HashMap map ;
HashMap temp;
private Integer ID;
String name ;
boolean isItNull =false;
public static void main(String[] args) {
new PlayerInfo();
}
PlayerInfo(){
try {
openTheOutPutObjectStreamer();
openTheInPutObjectStreamer();
initializeHashMap();
}catch (Exception e){
e.printStackTrace();
}
}
//here I initialize it in separated method
private void openTheOutPutObjectStreamer()throws IOException{
out =new ObjectOutputStream(new FileOutputStream(userData));
}
//same here I initialize it in separated method
private void openTheInPutObjectStreamer()throws IOException{
in =new ObjectInputStream(new FileInputStream(userData));
}
#SuppressWarnings("unchecked")
private void initializeHashMap(){
try {
if (isItNull){
temp =new HashMap<Integer,PlayerInfo>();
}else {
map =new HashMap<Integer,PlayerInfo>();
temp = (HashMap<Integer, PlayerInfo>) in.readObject();
in.close();
}
}catch (Exception e){
isItNull =true;
initializeHashMap();
}
}
#SuppressWarnings("unchecked")
private void createInfo()throws IOException{
System.out.println("Ok we are in create info so write your ID:-");
ID =10;
String scnS ="Mohammed";
System.out.println("Write your name");
map.put(ID,new PlayerInfo(scnS));
temp.putAll(map);
System.out.println("Saving....");
out.writeObject(temp);
out.close();
}
public PlayerInfo(String name){
this.name =name;
}
}
if you see it the difference is only separate the Object Input/Output to a method and call them
and I am sorry I am a newbie in this website
I don't know a lot about IO but it seems like I cant separate it to methods and call it?
The problem is that in your first code you (correctly) open an input stream uses it and then closes it before doing anything else to the same file but in your second code version you also open the output stream on the same file before having read it and that output stream puts the marker (where to read or write) at the end of the file so when you use your input stream you get an End of file error.
Changing you code to this should work
openTheInPutObjectStreamer();
initializeHashMap();
openTheOutPutObjectStreamer();

EOFException using readObject() deserializing an ArrayList

I'm trying to serialize an instance from a class using inheritance.
And this is the class where I try to serialize the data
public class Serializacion {
static int agregarProfeTitular(ProfesorTitular p){
int status = 0;
try {
FileOutputStream fos = new FileOutputStream("profestitulares.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
ArrayList pi = conseguirTodosProfesTitulares();
pi.add(p);
oos.writeObject(pi);
oos.close();
fos.close();
status = 1;
} catch (IOException e) {
System.out.println("Error al agregar el prof titular..."+Arrays.toString(e.getStackTrace()));
}
return status;
}
static ArrayList<ProfesorTitular> conseguirTodosProfesTitulares(){
ArrayList<ProfesorTitular> pi = new ArrayList<ProfesorTitular>();
try {
FileInputStream fis = new FileInputStream("profestitulares.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
pi = (ArrayList<ProfesorTitular>) ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
System.out.println("Error al conseguir a los profes titulares..."+e);
}
return pi;
}
}
At the end the try-catch throws me
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2950)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1534)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:427)
at profesores.Serializacion.conseguirTodosProfesTitulares(Serializacion.java:69)
at profesores.Serializacion.agregarProfeTitular(Serializacion.java:46)
The idea is that when I want to write some data in my file first I get the data that already exists parsing it as an arraylist and then i return that arraylist and i just add the new data. It works writing the file, but reading it doesnt work.
EDIT:
This is the class code that I try to serialize:
public class ProfesorTitular extends Profesor {
int horasBase;
public ProfesorTitular(int id, String nombre, String clase, int horasBase) {
super(id, nombre, clase);
this.horasBase = horasBase;
}
public int getHorasBase() {
return horasBase;
}
public void setHorasBase(int horasBase) {
this.horasBase = horasBase;
}
}
You create a FileOutputStream for the very poorly named file profestitulares.txt. Serialized data is not text and should not be saved in files with the .txt extension.
This creates an empty file.
You then create an ObjectOutputStream around this stream, which writes the object stream header.
You then create a FileInputStream for the same file, which is now empty apart from the object stream header, whatever its state may have previously been.
You then try to create an ObjectInputStream around this, which fails, because there is a stream header but no objects in this logically empty file.
Solution: read the objects from the file before you create the new one.

Error while file reading

I wanna make an ArrayList of objects of my own class named Room and store it to file. I have successfully wrote it but when I read it back to ArrayList it gives me the following error
error: incompatible types
temp_read=filereader.readObject();
^
required: Room
found: Object
My code:
public class Room implements Serializable
{
public String room_number="";
public String teacher_name="";
public String Day_of_class="";
public String class_name="";
public My_Time start_time;
public My_Time end_time;
public Room()
{
room_number="";
teacher_name="";
Day_of_class="";
class_name="";
start_time=new My_Time();
end_time=new My_Time();
}
public Room(String r_name ,String t_name ,String cl,String day,
int hr1,int min1,String am1,int hr2,int min2,String am2 )
{
room_number=r_name;
teacher_name=t_name;
Day_of_class=day;
class_name=cl;
start_time=new My_Time(hr1,min1,am1);
end_time=new My_Time(hr2,min2,am2);
}
public void file_room_writer(/* ArrayList<Room> temp_room ,*/String str )
{
/// file writing handling`enter code here`
//--------------------------------------------------
// Room a1 =temp_room;
try {
File file = new File(str+".txt");
FileOutputStream file_stream=new FileOutputStream(file);
ObjectOutputStream fileWriter = new ObjectOutputStream(file_stream);
fileWriter.writeObject(class_storing);
fileWriter.close();
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null,"Exception at file writing ");
}
}
public void file_room_reader(String str )
{
/// file handlingg
//--------------------------------------------------
ArrayList<Room> contain_room ;
try {
File file = new File(str+".txt");
FileInputStream file_stream=new FileInputStream(file);
ObjectInputStream filereader = new ObjectInputStream(file_stream);
temp_read=filereader.readObject();
contain_room=(ArrayList<Room>)filereader.readObject();
filereader.close();
}
catch(Exception e1)
{
e1.getStackTrace();
JOptionPane.showMessageDialog(null,"Exception at file Reading ");
}
}
The readObject method returns an object - you have to try and cast it to a Room.
temp_read = (Room) filereader.readObject();
readObject() returns Object , you'll have to downcast it to the type of temp_read.
Assuming Room is the type of temp_read
temp_read = (Room) filereader.readObject();

Serializing objects with hashMap

This is my first time i try objects serializing.
My problem is that when i call for saving new objects(Reminder.java objects) it saves them in the hash map but when i load it gives me the properties of the last saved object.
So my question is:
1.Saving - How do i "append" objects to a file ?
2.Loading - how to iterate through them and get the right object (using the key class type MyDateClass)
. Example will be welcomed. Thank you.
public void save(MyDateClass chosenDate, String string){
System.out.println("Trying to save");
reminderMap.put(chosenDate, string);
//serializing an object :
this.dateReminder = chosenDate;
this.reminder = string;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/reminder.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/reminder.ser. ");
}catch(IOException i)
{
i.printStackTrace();
}
}
public String Load(MyDateClass chosenDate){
System.out.println("Trying to load");
this.reminder = reminderMap.get(chosenDate);
System.out.println(this.reminder);
// deserialize
Reminder e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/reminder.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Reminder) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
}catch(ClassNotFoundException c)
{
c.printStackTrace();
}
return e.reminder;
}
}
I did a demo and unit test for you, currently I use java.util.Date to substitute your SomeDate class .
update: 2013-12-31
I am not trying to make things complex,but I really feel it is my responsibility to not mislead others,so I try to fixed the code again.Currently, HashMap can't be append,please improve it.Thanks!
this code refactored from your code:
import java.io.*;
import java.util.*;
/**
* refactored by your code
* append object stream haven't realized,please help
* 2013-12-31
*/
public class Reminder implements Serializable {
public static void main(String[] args) {
//do some initialization
Reminder re = new Reminder();
re.put(new Date(System.currentTimeMillis()), "Hope it work!");
re.put(new Date(System.currentTimeMillis()+100), "it work!");
re.put(new Date(System.currentTimeMillis()+200), "Wake up!");
//save to file ,using append mode
String filpath = "/tmp/reminder.ser";
re.save(filpath,true);
//load from file and iterate the key-value pair
Reminder reLoad = Reminder.Load(filpath);
if(reLoad != null) {
Iterator<Map.Entry<Date,String>> it = reLoad.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Date,String> entry = it.next();
System.out.format("reminder: %tc---%s%n",entry.getKey(),entry.getValue());
}
}
}
public Set<Map.Entry<Date,String>> entrySet() {
return reminderMap.entrySet();
}
public void put(Date chosenDate, String string) {
reminderMap.put(chosenDate, string);
}
public String get(Date chosenDate) {
return reminderMap.get(chosenDate);
}
/**
* serializing an object
* #param filePath path to save file
* #param append indicate whether append or not
*/
public void save(String filePath,boolean append){
System.out.println("Trying to save");
try
{
ObjectOutputStream out = new ObjectOutputStream
( new FileOutputStream(filePath,append));
out.writeObject(this);
out.close();
System.out.printf("Serialized data is saved in "+filePath);
}catch(IOException e)
{
e.printStackTrace();
}
}
/**
* deserialize ,load from file and rebuild object
* #param filePath the path from where to load
* #return a new Object
*/
public static Reminder Load(String filePath) {
System.out.println("Trying to load");
Reminder reminder = null;
try
{
ObjectInputStream in = new ObjectInputStream
(new FileInputStream(filePath));
reminder = (Reminder) in.readObject();
in.close();
}catch(IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
return reminder;
}
private static final long serialVersionUID = 1L;
private Map<Date,String> reminderMap = new HashMap<>();
}

Load/Store Objects in file in Java

I want to store an object from my class in file, and after that to be able to load the object from this file. But somewhere I am making a mistake(s) and cannot figure out where. May I receive some help?
public class GameManagerSystem implements GameManager, Serializable {
private static final long serialVersionUID = -5966618586666474164L;
HashMap<Game, GameStatus> games;
HashMap<Ticket, ArrayList<Object>> baggage;
HashSet<Ticket> bookedTickets;
Place place;
public GameManagerSystem(Place place) {
super();
this.games = new HashMap<Game, GameStatus>();
this.baggage = new HashMap<Ticket, ArrayList<Object>>();
this.bookedTickets = new HashSet<Ticket>();
this.place = place;
}
public static GameManager createManagerSystem(Game at) {
return new GameManagerSystem(at);
}
public boolean store(File f) {
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(games);
oos.writeObject(bookedTickets);
oos.writeObject(baggage);
oos.close();
fos.close();
} catch (IOException ex) {
return false;
}
return true;
}
public boolean load(File f) {
try {
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
this.games = (HashMap<Game,GameStatus>)ois.readObject();
this.bookedTickets = (HashSet<Ticket>)ois.readObject();
this.baggage = (HashMap<Ticket,ArrayList<Object>>)ois.readObject();
ois.close();
fis.close();
} catch (IOException e) {
return false;
} catch (ClassNotFoundException e) {
return false;
}
return true;
}
.
.
.
}
public class JUnitDemo {
GameManager manager;
#Before
public void setUp() {
manager = GameManagerSystem.createManagerSystem(Place.ENG);
}
#Test
public void testStore() {
Game g = new Game(new Date(), Teams.LIONS, Teams.SHARKS);
manager.registerGame(g);
File file = new File("file.ser");
assertTrue(airport.store(file));
}
}
The solution of this problem is that when you are using other objects, let say class A, into a collection like HashMap and want to serialize the HashMap object, then implement the interface Serializable for class A like this:
class A implements Serializable {
}
...
HashMap<Integer,A> hmap;
...
Otherwise that object will not be serializable.
I hope it will solve this problem now.
Try oos.flush() before you close it.
Please remenber that the whole object graph is persisted during serialize. If you have some references to GUI classes for example, you either have to make them serializable, too, or tag them as "transient", so Java won't serialize them.

Categories

Resources