序列化 List<List<String>> 无限循环迭代器.hasNext() JAVA



我一直在尝试用Java序列化List<List< String >>,但我的代码在循环中被卡住了。这是代码:

public void Serializing(List<List<String>> player,File file ) throws IOException{

try {
fileOut=new FileOutputStream(file);
out= new ObjectOutputStream(fileOut);
Iterator <List <String>> it=player.listIterator();
while(it.hasNext()){ //Somehow if i don't put this just adds my first element 
out.writeObject(player.listIterator().next());
}
fileOut.close();
out.close();

} catch (FileNotFoundException ex) {
Logger.getLogger(ManejoInformacion.class.getName()).log(Level.SEVERE, null, ex);
}
}

我正在添加反序列化方法,以防

public  List<List<String>> deserializable(File file) throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream in;
List<List<String>> info;
try (FileInputStream fileIn = new FileInputStream(file)) {
in =new ObjectInputStream(fileIn);
info = new ArrayList<>();
info =(List<List<String>>)in.readObject();
}      in.close();
return info;
}

希望这就足够了!谢谢:(

此处:

out.writeObject(player.listIterator().next());

您正在创建一个新的迭代器。但是您已经有了一个迭代器,您需要使用它来更新它的状态。

out.writeObject(it.next());

否则,it.hasNext()保持为true,因为您没有从it中获取项目。

或者,去掉对迭代器的所有引用,去掉while循环,只使用for循环:

for (List<String> item: player) {
out.writeObject(item);
}

for循环隐式地处理迭代器,所以您不必这样做

最新更新