Oppo
Oppo

Reputation: 43

How to read all objects from ObjectInputStream

I have a file with some info how can I read all info?

Name names;    
try (FileInputStream fileInputStream = new FileInputStream(file)) {
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            names = (Name) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

Upvotes: 3

Views: 9820

Answers (1)

NoDataFound
NoDataFound

Reputation: 11949

You have several solution, all depending on the input:

  • You can iterate until the stream is fully consumed: I think that is the worse solution out of those I provide you. It is worse because you are checking if EOF was reached, whilst you should know when you're done (eg: your file format is wrong).

    Set<Name> result = new HashSet<>();
    try { 
      for (;;) { 
        result.add((Name)objectInputStream.readObject());
      }
    } catch (EOFException e) {
      // End of stream
    } 
    return result;
    
  • When producing the input, serialize a collection and invoke readObject() on it. Serialization should be able to read the collection, as long as each object implements Serializable.

    static void write(Path path, Set<Name> names) throws IOException {
      try (OutputStream os = Files.newOutputStream(path);
           ObjectOutputStream oos = new ObjectOutputStream(os)) {
        oos.writeObject(names);    
      }       
    } 
    
    static Set<Name> read(Path path) throws IOException {
      try (InputStream is = Files.newInputStream(path);
           ObjectInputStream ois = new ObjectInputStream(is)) {
        // WARN Files.newInputStream is not buffered; ObjectInputStream might
        // be buffered (I don't remember).
        return (Set<Name>) ois.readObject();
      }
    }
    
  • When producing the input, you can add a int indicating the number of object to read, and iterate over it: this is useful in case where you don't really care of the collection (HashSet). The resulting file will be smaller (because you won't have the HashSet metadata).

    int result = objectInputStream.readInt();
    Name[] names = new Name[result]; // do some check on result!
    for (int i = 0; i < result; ++i) {
      names[i] = (Name) objectInputStream.readObject();
    }
    

Also, Set are good, but since they remove duplicate using hashCode()/equals() you may get less object if your definition of equals/hashCode changed after the fact (example: your Name was case sensitive and now it is not, eg: new Name("AA").equals(new Name("aa"))).

Upvotes: 5

Related Questions