文件读取时出错

时间:2015-12-29 18:24:56

标签: java arraylist

我想创建一个名为Room的我自己的类的对象的ArrayList并将其存储到文件中。我已经成功写了它但是当我把它读回ArrayList时它给了我以下错误

error: incompatible types
                temp_read=filereader.readObject();
                                               ^
required: Room
found:    Object  

我的代码:

public class Room implements Serializable
{
    public String room_number="";
    public String teacher_name="";
    public String Day_of_class="";

    public String class_name="";
    public My_Time start_time;
    public My_Time end_time;
    public Room()
    {
        room_number="";
        teacher_name="";
        Day_of_class="";
        class_name="";
        start_time=new My_Time();
        end_time=new My_Time();
    }
    public Room(String  r_name ,String t_name ,String cl,String day,
                int hr1,int min1,String am1,int hr2,int min2,String am2 )
    {
        room_number=r_name;
        teacher_name=t_name;
        Day_of_class=day;
        class_name=cl;
        start_time=new My_Time(hr1,min1,am1);
        end_time=new My_Time(hr2,min2,am2);
    }

public void file_room_writer(/* ArrayList<Room> temp_room ,*/String str )
{

    /// file writing handling`enter code here`
    //--------------------------------------------------
    //  Room a1 =temp_room; 
    try {
        File file = new File(str+".txt");
        FileOutputStream file_stream=new FileOutputStream(file);
        ObjectOutputStream fileWriter = new ObjectOutputStream(file_stream); 
        fileWriter.writeObject(class_storing);  
        fileWriter.close();
    }
    catch(Exception e1)
    {
        JOptionPane.showMessageDialog(null,"Exception at file writing ");
    }           
}

public void file_room_reader(String str )
{
    /// file handlingg
    //--------------------------------------------------
    ArrayList<Room> contain_room ;
    try {
        File file = new File(str+".txt");
        FileInputStream file_stream=new FileInputStream(file);
        ObjectInputStream filereader = new ObjectInputStream(file_stream);

        temp_read=filereader.readObject();
        contain_room=(ArrayList<Room>)filereader.readObject();
        filereader.close();
    }
    catch(Exception e1)
    {
        e1.getStackTrace();
        JOptionPane.showMessageDialog(null,"Exception at file Reading ");
    }
}

2 个答案:

答案 0 :(得分:2)

readObject方法返回一个对象 - 您必须尝试将其强制转换为Room。

temp_read = (Room) filereader.readObject();

答案 1 :(得分:0)

readObject()返回Object,您必须将其转发为temp_read类型。

假设Roomtemp_read

的类型
temp_read = (Room) filereader.readObject();