从文件中读取对象

时间:2014-02-11 20:31:18

标签: java serialization java-io

我从文件Java中读取对象时遇到问题。

filearraylist<projet>

这是保存对象的代码:

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();
}

这是从文件::

中读取对象的代码
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();
}

写作正常。问题是阅读...它没有读取任何对象(projet)可能是什么问题?

1 个答案:

答案 0 :(得分:0)

正如EJP在评论和this SO post中提到的那样。如果您计划在单个文件中编写多个对象,则应编写自定义ObjectOutputStream,因为在写入第二个或第n个对象头信息时,该文件将被破坏。
正如EJP所建议的那样写为ArrayList,因为ArrayList已经是Serializable,所以你不应该有问题。如

out.writeObject(file)并将其读回ArrayList b = (ArrayList) in.readObject();
由于某种原因,如果你不能把它写成ArrayList。创建custom ObjectOutStream为

class MyObjectOutputStream extends ObjectOutputStream {

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

@Override
protected void writeStreamHeader() {}

}

并将您的writeObject更改为

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();

}

并将readObject更改为

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();
        }
    }