简体   繁体   中英

reading objects from file

I have a problem with reading objects from file Java.

file is an arraylist<projet>

This is the code of saving objects :

try {
    FileOutputStream fileOut = new FileOutputStream("les projets.txt", true);
    ObjectOutputStream out = new ObjectOutputStream(fileOut);

    for (projet a : file) {
        out.writeObject(a);
    }
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}

And this is the code of reading objects from file ::

try {
    FileInputStream fileIn = new FileInputStream("les projets.txt");
    ObjectInputStream in = new ObjectInputStream(fileIn);

    while (in.available() > 0){
        projet c = (projet) in.readObject();

        b.add(c);
    }

    choisir = new JList(b.toArray());
    in.close();
} catch (Exception e) {
    e.printStackTrace();
}

Writing is working properly. The problem is the reading... it does not read any object (projet) What could be the problem?

As mentioned by EJP in comment and this SO post . if you are planning to write multiple objects in a single file you should write custom ObjectOutputStream , because the while writing second or nth object header information the file will get corrupt.
As suggested by EJP write as ArrayList , since ArrayList is already Serializable you should not have issue. as

out.writeObject(file) and read it back as ArrayList b = (ArrayList) in.readObject();
for some reason if you cant write it as ArrayList. create custome ObjectOutStream as

class MyObjectOutputStream extends ObjectOutputStream {

public MyObjectOutputStream(OutputStream os) throws IOException {
    super(os);
}

@Override
protected void writeStreamHeader() {}

}

and change your writeObject as

try {
        FileOutputStream fileOut= new FileOutputStream("les_projets.txt",true);
        MyObjectOutputStream out = new MyObjectOutputStream(fileOut );

         for (projet a : file) {
    out.writeObject(a);
}
        out.close();
    }

    catch(Exception e)
    {e.printStackTrace();

}

and change your readObject as

ObjectInputStream in = null;
    try {
        FileInputStream fileIn = new FileInputStream("C:\\temp\\les_projets1.txt");
        in = new ObjectInputStream(fileIn );

        while(true) {
            try{
                projet c = (projet) in.readObject();
                b.add(c);
            }catch(EOFException ex){
                // end of file case
                break;
            }

        }

    }catch (Exception ex){
        ex.printStackTrace();
    }finally{
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

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