2013-12-08 30 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();