質問

I started developing an app for my class, which has a request that I need to save objects from a list in a .txt file. It seems to be working, but when I do that, it saves only one object that I entered. I don't know what the solution is. My code is below. P.S. I am using gui to add my objects in a list.

List<Korisnik> listaK=Kontroler.vratiObjekatKontroler().vratiKorisnika();
   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));
             out.close();
          }

        } catch (IOException ex) {
            ex.printStackTrace();
        }
役に立ちましたか?

解決

for (int i = 0; i < listaK.size(); i++) { 
    out.writeObject(listaK.get(i)); 
    out.close(); 
}

You are closing the output stream once you have written the first object. This way you cannot write anything else into it. Move the out.close() out of for loop.

他のヒント

You are closing your stream inside the for loop. I recommend:

FileOutputStream fos = null;
ObjectOutputStream out = null;

try {
    fos = new FileOutputStream(new File("output.txt"));
    out= new ObjectOutputStream(fos);

    for (int i = 0; i < listaK.size(); i++) {
        out.writeObject(listaK.get(i));
    }
} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (out != null) out.close;
    if (fos != null) fos.close;
}

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top