简体   繁体   中英

Read many ArrayList Objects out of File with ObjectInputStream?

i write ArrayLists into a file. I read it with FileInputStream. But always just the "first" ArrayList is appears by reading. I tried it with readInt() / wirteInt(), and loops, but there were always thrown exceptions, by calling readInt() --> EOF I want to read all ArrayList from this File into an ArrayList. My application needs to be persistent, so i serialized the ArrayLists.

write into file:

  try { FileOutputStream fos = new FileOutputStream(_cache, true); ObjectOutputStream os = new ObjectOutputStream(fos); // os.writeInt(newValueList.size()); // Save size first os.writeObject(newValueList); os.flush(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

read from file:

 List cachedValueList = new ArrayList<String>();
    ObjectInputStream o = new ObjectInputStream(new FileInputStream("caching.io"));
  //  int count = o.readInt(); // Get the number of regions

    try {

            cachedValueList.add(o.readObject());

    } catch (EOFException e) {
        o.close();
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

If you are writing the same list many times, it will only write the list once. After that it will use the same reference but the contents will be the same (this is true of any object)

If you call reset() between writeObject() it will send a fresh copy of the list each time.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM