Hoping that you are using at least Java SE 7 :) you can take advantage of try-with-resources so you don't need to care about closing "resources":
try (
FileOutputStream fos = new FileOutputStream(new File("output.txt"));
ObjectOutputStream out= new ObjectOutputStream(fos)
){
for (int i = 0; i < listaK.size(); i++) {
out.writeObject(listaK.get(i));
}
} catch (IOException ex) {
ex.printStackTrace();
}
The try-with-resources statement contains the FileOutputStream
and ObjectOutputStream
object declarations that are separated by a semicolon. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the FileOutputStream
and ObjectOutputStream
objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.