2013-12-08 29 views
1

我的程序基本上是一個日常計劃。在Java中使用ObjectInputStream從文件中檢索字符串數組?

時間表由ObjectOutputStream按月份和年份保存在文件中。檢查

日程安排按天排列。檢查

時間表由ObjectInputStream檢索。這是我遇到問題的地方。

public class Calendar { 
public String date; 
public String[] schedule = new String[31]; 
Calendar(){ 


} 

public String retrieve(int month, int day, int year) { 
    date = Integer.toString(month) + "-"+ Integer.toString(year) + ".txt"; 

    try { 
     ObjectInputStream input = new ObjectInputStream(new 
FileInputStream(date)); 
     input.readObject(); 
     schedule = input;  
//This is where I have the error obviously schedule is a string array and 
//input is an ObjectInputStream so this wont work 
     input.close(); 
     return schedule[day-1]; 

    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return "File not found"; 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return "IOException"; 
    } catch (ClassNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return "ClassNotFound"; 
    } 

} 

public void save(int month, int day, int year, JTextArea entry) { 
    date = Integer.toString(month) + "-"+ Integer.toString(year) + ".txt"; 
    schedule[day-1]= entry.getText(); 
    try { 
     ObjectOutputStream output = new ObjectOutputStream(new 
FileOutputStream(date)); 
     output.writeObject(schedule); 
     output.close(); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 



} 

的時間表將像

entry.setText(calendar.retrieve(month,day,year)); 

回答

5
ObjectInputStream input = new ObjectInputStream(new FileInputStream(date)); 

OK顯示在使用的東西的文本區域。

input.readObject(); 

毫無意義。此方法返回讀取的對象。您需要將其存儲到變量中。

schedule = input; 

也毫無意義。 input是您即將關閉的ObjectInputStream。將它保存在另一個變量中是徒勞的。

//This is where I have the error obviously schedule is a string array and 
//input is an ObjectInputStream so this wont work 
input.close(); 

應該

schedule = (String[])input.readObject();