我是新人,我只懂一点英语。我的问题是我必须做一个多线程服务器和一个Client类来将很多客户端传递给一个服务器。我将我的客户端保存在一个hashmap中,在添加到hashmap后我使用一种方法写入一个文件(HashMap是可序列化的,我使用单例模式使hashmap成为全局)。问题是当我尝试从我的文件中读取时,Java会抛出一个EOFException,我不知道为什么。
这是我的代码:
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);
}
}
问题在于:
in = new ObjectInputStream(fileIn);
这是一个例外:
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)
我希望你能帮助我,对不起我的英语:)
答案 0 :(得分:0)
您正尝试从空文件初始化ObjectInputStream
。