Java Serialization writeObject失败而没有定义变量

时间:2011-11-27 17:02:52

标签: java serialization java-io

由于一些奇怪的原因,我可以将我的对象写入文件,如果分解为变量或字符串,但不是如教程中显示为一个实体对象。

示例成功:

public Book add(Book book){
        try{
        FileOutputStream fos = new FileOutputStream("stream.txt");
        ObjectOutputStream output = new ObjectOutputStream(fos);
        output.writeObject(book.getString1());
        output.writeObject(book.getString2());
        output.writeObject(book.getString3());
        output.flush();
        output.close();
        }catch(Exception e){
            System.out.print("Falure to write!");
      }
        return book;
    }

当我尝试编写对象时,以下代码完全轰炸并跳转到捕获:

示例失败:

public Book add(Book book){
        try{
        FileOutputStream fos = new FileOutputStream("stream.txt");
        ObjectOutputStream output = new ObjectOutputStream(fos);
        output.writeObject(book);
        output.flush();
        output.close();
        }catch(Exception e){
            System.out.print("Falure to write!");
      }
        return book;
    }

1 个答案:

答案 0 :(得分:1)

Book类应实现Serializable接口

另外,错误信息是什么?

}catch(Exception e){
    System.out.println(e);
}