I've been trying to serialize a List<List< String >>
in Java but my code gets stucks in a loop. Here's the code:
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);
}
}
I'm adding the deserializable method just in case
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;
}
Hope this is enough: Thank you :)
Here:
out.writeObject(player.listIterator().next());
you're creating a new iterator. But you already had an iterator, and you need to use that one so its state is updated.
out.writeObject(it.next());
Otherwise it.hasNext()
stays true because you're not taking items from it
.
Alternatively, get rid of all reference to iterators, get rid of the while-loop, and just use a for-loop:
for (List<String> item: player) {
out.writeObject(item);
}
The for-loop handles the iterator implicitly, so you don't have to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.