使用Java中的ObjectInputStream从文件中检索String数组?

use*_*509 1 java arrays string exception 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();
    }

}



}
Run Code Online (Sandbox Code Playgroud)

时间表将使用类似的内容显示在文本区域中

entry.setText(calendar.retrieve(month,day,year));
Run Code Online (Sandbox Code Playgroud)

use*_*421 5

ObjectInputStream input = new ObjectInputStream(new FileInputStream(date));
Run Code Online (Sandbox Code Playgroud)

好.

    input.readObject();
Run Code Online (Sandbox Code Playgroud)

无意义.此方法返回已读取的对象.您需要将其存储到变量中.

    schedule = input;
Run Code Online (Sandbox Code Playgroud)

也毫无意义.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();
Run Code Online (Sandbox Code Playgroud)

它应该是

schedule = (String[])input.readObject();
Run Code Online (Sandbox Code Playgroud)