0

Please have a look at below code

public class xina {

    static name[] Name;

    public static void main(String[] args) throws Exception {
        Name = new name[3];
        Name[0] = new name("Hugh", "Jackman");
        Name[1] = new name("John", "TRavolta");
        Name[2] = new name("Megh", "Ryne");

        File ff = new File("object.txt");

        FileOutputStream fo = new FileOutputStream(ff.getName());
        ObjectOutputStream oo = new ObjectOutputStream(fo);

        for (name dd : Name) {
            System.out.println(dd.getfistName() + " " + dd.getlastName());
            oo.writeObject(dd);
        }

        oo.close();

        FileInputStream fi = new FileInputStream(ff.getName());
        ObjectInputStream oi = new ObjectInputStream(fi);

        name hh;
        try {
            while ((hh = (name) oi.readObject()) != null) {
                System.out.println(hh.fistName);
            }
        } catch (EOFException e) {
            System.out.println("file ended");
        }

    }
}

here "name" is class which save first name and last name. How can i read the file without using exception. My point is it is trying to read when no more objects exists look like null check is not sufficing the need.

THanks in advance.

Andrew Stubbs
  • 4,322
  • 3
  • 29
  • 48
Nomad
  • 1,019
  • 4
  • 16
  • 30

2 Answers2

1
while ((hh = (name) oi.readObject()) != null) {

The problem is here. readObject() returns null if you wrote a null, and not otherwise. The correct test for reading past end of stream is to catch EOFException.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

Problem here is that the method InputStream#readObject does not return null object past EOF it always throws an Exception. The Simple solution to that is while serializing pass the size of the array first and read the size first and then the array of that size while de-serializing.

So while writing:

oo.writeObject(new Integer(Name.length));

for (name dd : Name) {
        System.out.println(dd.getfistName() + " " + dd.getlastName());
        oo.writeObject(dd);
}

while reading:

ObjectInputStream oi = new ObjectInputStream(fi);

Integer size = oi.readObject();
name hh;
    for (int i=0;i<size;i++) {
        hh= (Name) oi.readObject();
        System.out.println(hh.fistName);
    }

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33