-1
所以,我需要一些幫助。我有一個class Book
,我想將我的書籍對象保存爲Stream
,然後閱讀此Stream
文件,以便我可以從那裏搜索我的對象。我寫了我的代碼,但它給了我一些錯誤,我可以弄清楚如何打印我的書籍價值。 所以這是我的書類Java Streams讀取文件並打印文件上的對象
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();}
}
}
,這是我的搜索類:
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();
}
}
}
}
什麼錯誤?請明確點。 – bcsb1001
[爲什麼Java需要Serializable接口?](http://stackoverflow.com/questions/441196/why-java-needs-serializable-interface) – fabian
它給我錯誤當我在命令中寫入文件時.writeObject(本); – Wesdom