Question

My program is basically a daily planner.

The schedule is saved in files by month and year by ObjectOutputStream. check

The schedule is arranged in an array by day. check

The schedule is retrieved by ObjectInputStream. This is where I have problems.

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

}



}

The schedule will be displayed in a text area using something like

entry.setText(calendar.retrieve(month,day,year));
Was it helpful?

Solution

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

OK.

    input.readObject();

Pointless. This method returns the object that was read. You need to store it into a variable.

    schedule = input;

Also pointless. input is an ObjectInputStream that you're about to close. Saving it in another variable is futile.

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

It should be

schedule = (String[])input.readObject();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top