Java Streams读取文件和在文件上读取的打印对象

时间:2016-03-06 13:41:26

标签: java object stream

所以,我需要一些帮助。我有sudo apt-get install php5-xsl,我想将我的图书对象保存到class Book,然后阅读此Stream文件,以便我可以从那里搜索我的对象。我写了我的代码,但它给了我一些错误,我可以弄清楚如何打印我的书籍值。 所以这是我的Book类

Stream

这是我的搜索类:

public class Book {

    private Date arr;
    private Date depp;
    private Type room;
    private boolean breakfast = false;
    private Person data;
    private ObjectOutputStream out;

    public Book(String name, String surename, String phone,Date arr, Date depp, Type room, boolean breakfast) {
        data = new Person(name,surename,phone);
        this.arr = arr;
        this.depp = depp;
        this.room = room;
        this.breakfast = breakfast;

    }
    public void writeObjToFile(){//here i save my object to stream it gives me error, i call this method after i create my book object to main
        try{
            out = new ObjectOutputStream(new FileOutputStream("books.txt"));
            out.writeObject(this);    
        }
        catch(FileNotFoundException e){
            System.err.println("File not Found");
            e.printStackTrace();
        }catch(IOException e){
    System.err.println("IOException");

        e.printStackTrace();}
    }

}

1 个答案:

答案 0 :(得分:0)

Book应该实现Serializable

检查API https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeObject%28java.lang.Object%29

另外,从Book类中删除out成员,因为它也不是Serializable。