将对象数组保存到文本文件中

时间:2015-03-15 13:42:01

标签: java arrays object

我正在尝试将数组对象(Room)保存为.txt文件。我对序列化并不熟悉,但我尽可能地使用它来将对象写入文件。但是,我每次都会收到此错误代码:

java.io.NotSerializableException: hotelobjects.Room
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1378)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at hotelobjects.HotelObjects.storeData(HotelObjects.java:81)
at hotelobjects.HotelObjects.main(HotelObjects.java:50) 

这是主要代码:

public class HotelObjects {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws Exception {
    String command;

    Scanner input = new Scanner(System.in);

    Room[] myHotel = new Room[10];
    for (int x = 0; x < myHotel.length; x++) {
    myHotel[x] = new Room();
    }

    String roomName;
    int roomNum = 0;

    while (roomNum < 11) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter command : ");
        command = input.next();
        command = command.toLowerCase();

        if (command.charAt(0) == 'v') {
            viewCustomers(myHotel);
        }

        if (command.charAt(0) == 'a') {
            addCustomers(myHotel);
        }

        if (command.charAt(0) == 'e') {
            emptyRooms(myHotel);
        }

        if (command.charAt(0) == 's') {
            storeData(myHotel);
        }
    }
}

private static void viewCustomers(Room hotelRef []) {
    for (int x = 0; x < 10; x++) {
            System.out.println("room " + x + " occupied by " + hotelRef[x].getName());
        }
}

private static void addCustomers(Room myHotel[]) {
    String roomName;
    int roomNum;
    System.out.println("Enter room number (0-10) or 11 to stop:");
    Scanner input = new Scanner(System.in);
        roomNum = input.nextInt();
        System.out.println("Enter name for room " + roomNum + " :");
        roomName = input.next();
        myHotel[roomNum].setName(roomName);
}

private static void emptyRooms(Room[] myHotel) {
    for (int x = 0; x < 10; x++ )
        if (myHotel[x].getName().equals("e"))System.out.println("room " + x + " is empty");
}

private static void storeData(Room [] myHotel) {
     try{
     FileOutputStream fos= new FileOutputStream("C:\\Users\\Ganz\\Documents\\NetBeansProjects\\HotelObjects\\HotelObject.txt");
     ObjectOutputStream oos= new ObjectOutputStream(fos);
     oos.writeObject(myHotel);
     oos.close();
     fos.close();
   }catch(IOException ioe){
        ioe.printStackTrace();
    }
}

}

2 个答案:

答案 0 :(得分:0)

答案已经在例外消息中。我错过了hotelobjects.Room的代码,但我敢打赌它没有实现Serializable。解决方案是简单地使Room实现Serializable。

答案 1 :(得分:0)

听起来你还没有实现Serializable接口 您的Room课程应如下所示:

public class Room implements Serializable{
    public Room(){
        //...
    }
}