-1

So guys i need some help. I have a class Book and i want to save my books object to a Stream and then read this Stream file so i can search my objects from there. I have written my code but it gives me some errors and i can figure out how to print my books values . So this is my Book class

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

}

and this is my Search class :

public class Search {
    private FileInputStream fis=null;
    private String filename;

    public Search(String filename){
        this.filename = filename;

        File file = new File(filename);

        try {
            fis = new FileInputStream(file);

            System.out.println("Total file size to read (in bytes) : "
                    + fis.available());

            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                System.out.print((char) content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
Wesdom
  • 1
  • 1

1 Answers1

0

Book should implement Serializable

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

Also, remove the out member from Book class because it's not Serializable either.

Lluis Martinez
  • 1,963
  • 8
  • 28
  • 42