javaserializationobjectinputstreameofexception

EOFException initializing an ObjectInputStream


I am new and I only know a little of english. Well my problem is that I have to do a Multithreading server and a Client class to communicate a lot of clients to one server. I am saving my clients in a hashmap and after adding to the hashmap I am using a method to write into a file (HashMap is serializable and I am using singleton pattern to make the hashmap global). The problem is when I try to read from my file, then Java throws me an EOFException and I don't know why.

This is my code:

import java.io.*;
import java.util.*;

public class MapaClients implements java.io.Serializable  {

private static MapaClients mapa= new MapaClients();

private Map<String,Client> clients= new HashMap<String,Client>();

private MapaClients(){}

public static MapaClients getInstance(){
    return mapa;
}

public void afegirMapa(String correu, Client client){
    clients.put(correu, client);
}

public Client existeix(String correu){
    if(clients.containsKey(correu)){
        return(clients.get(correu));
    }else{
        return(null);
    }
}

public void serializableGuardar(){
    try {
         FileOutputStream fileOut =new FileOutputStream("client.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(mapa);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in client.ser");
      } catch (IOException i) {
         i.printStackTrace();
      }
}

public void desserializableCarregar(){
    ObjectInputStream in;
      try {
         FileInputStream fileIn = new FileInputStream("client.ser");
         in = new ObjectInputStream(fileIn);
         boolean check=true;
         while (check) {
            try{
                mapa = (MapaClients) in.readObject();
            } catch(EOFException ex){
                in.close();
                check=false;
            }
         }
         in.close();
         fileIn.close();
      } catch (IOException i) {
         i.printStackTrace();
      } catch (ClassNotFoundException c) {
         c.printStackTrace();
      }
}

public void actualizar(Client client){
    clients.replace(client.getCorreu(), client);
}
}

The problem is here:

in = new ObjectInputStream(fileIn);

This is the exception:

java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Proves.MapaClients.desserializableCarregar(MapaClients.java:46)

I hope u can help me and sorry for my english :)


Solution

  • You are trying to initialize the ObjectInputStream from an empty file.