【问题标题】:ClassCastException During Object Reading from binary file to Array从二进制文件到数组的对象读取期间的 ClassCastException
【发布时间】:2018-06-24 12:04:05
【问题描述】:

我将我的类中的一个对象写入二进制文件,现在我只想读回对象数组。但我得到了一个错误。

我的问题是我无法将文件读入对象“aaa”。我想将它读入一个名为“aaa”的数组对象。下面是我得到的运行时异常。但是代码有意义没有错误。 read.object 返回一个对象类,我所做的只是将其转换为 (Customer[])。但我在下面得到了这个运行时错误。

这是我的代码

         Customer[] customer = new Customer[100]; 
     Customer[] aaa = new Customer[100];
         try{

        file2 = new java.io.FileInputStream("Appointments.bin");
        object2 = new java.io.ObjectInputStream(file2);

        aaa = (Customer[]) object2.readObject(); <--- I think this is where the error occurs

        for(Customer ddd : aaa)
            System.out.print(ddd);


        object2.close();
        file2.close();

    } catch(java.io.FileNotFoundException a){

        System.out.print("Appointments.bin File Not Found , Please Contact The Developer to fix this issue. Thank you.\n\n");
        System.exit(-1);

    } catch(java.io.IOException b){

    } catch(java.lang.ClassNotFoundException c){

        System.out.print("dsada");
    }

我的人类班级代码

public abstract class Human implements java.io.Serializable{

protected String firstName , lastName;
protected java.util.Date dateCreated = new java.util.Date();

public Human(){
}

public Human(String firstName , String lastName){
    this.firstName = firstName;
    this.lastName = lastName;
}

public void setFirstName(String firstName){
    this.firstName = firstName;
}


public void setLastName(String lastName){
    this.lastName = lastName;
}

public String getFirstName(){
    return firstName;
}

public String getLastName(){
    return lastName;
}


public String getFullName(){
    return firstName + " " + lastName + "\n";
}

@Override
public String toString(){
    return "First Name = " + firstName + "\nLast Name = " + lastName + "\nDate Created = " + dateCreated.toString() + "\n";

}

public abstract String getID();

}

我的客户类别代码

public class Customer extends Human implements java.io.Serializable {

private int code  = 1000;   
protected String customerID , day , time , service , carNo;


public Customer(){

}

public Customer(String firstName , String lastName , String service , String time , String day , String carNo){
     this.firstName = firstName;
     this.lastName = lastName;
     this.service = service;
     this.time = time;
     this.day = day;
     this.carNo = carNo;
     code++;
     customerID = "C" + code;
}

public String getService(){
    return service;
}

public String getTime(){
    return time;
}

public String getDay(){
    return day;
}

public String getCarNo(){
    return carNo;
}

@Override
public String getID(){
    return customerID;
}

public void setService(String service){
    this.service = service;
}

public void setTime(String time){
    this.time = time;
}

public void setDay(String day){
    this.day = day;
}

public void setCarNo(String carNo){
    this.carNo = carNo;
}

private void setID(String customerID){
   this.customerID = customerID;    
}

@Override
public String toString(){   
    return super.toString() + "CustomerID = " + customerID + "\n";

}    
}

客户注册的完整代码。它没有完成我只是围绕读写对象功能进行测试。所以是的,其中一些没有意义并且没有组织。

public static void customerRegistration(){         
         java.io.FileOutputStream file;
 java.io.FileInputStream file2;
 java.io.ObjectOutputStream object;
java.io.ObjectInputStream object2;
     Validation validation = new Validation();         
     Customer[] customer = new Customer[100];
     Scanner input = new Scanner(System.in);
     String string;

     int i = 0 , choice = 0, ww = 1;

     boolean value , lol = false , exception = false;

     ExceptionHandler handleEx = new ExceptionHandler();
     int year , day , month;
     Calendar date = Calendar.getInstance();
     date.setLenient(false); // is a method that will validate the date and throws an exception if its out of range
     do{

         try{

        file2 = new java.io.FileInputStream("Appointments.bin");
        object2 = new java.io.ObjectInputStream(file2);

        Customer[] aaa = (Customer[]) object2.readObject();

        for(Customer ddd : aaa)
            System.out.print(ddd);


        object2.close();
        file2.close();

    } catch(java.io.FileNotFoundException a){

        System.out.print("Appointments.bin File Not Found , Please Contact The Developer to fix this issue. Thank you.\n\n");
        System.exit(-1);

    } catch(java.io.IOException b){

    } catch(java.lang.ClassNotFoundException c){

        System.out.print("dsada");
    }
         customer[i] = new Customer();             
         do{

             System.out.print("Enter First Name : ");            
             customer[i].setFirstName(input.nextLine());           
             value = validation.validateName(customer[i].getFirstName()); 

         } while (value);             

         do{                             
             System.out.print("Enter Last Name : ");               
             customer[i].setLastName(input.nextLine());             
             value = validation.validateName(customer[i].getLastName());

         } while(value);  

         do{                 
             System.out.printf("\n\n%-20s  %-20s  %-20s\n\n" ,"Services" , "Time  Available" , "Days  Available" );
             System.out.printf("%-20s  %-20s  \n%-20s  %-20s  %-20s\n%-20s  %-20s  %-20s\n%-20s  %-20s  %-20s\n\n\n", "Repair" , "9.00am - 10.00am" ,  "Repaint" , "11.00am - 12.00pm" , "Monday - Sunday" , "Wax & Polish" , "1.00pm - 2.00pm" , "Monday - Sunday" , "Maintenance Service" , "3.00pm - 4.00pm" , "Monday - Sunday");       
             System.out.print("Enter A service based on numbers Ex (Repair = 1 , Repaint = 2 and so on) :");

             choice = handleEx.handle(input);
             input.nextLine(); // reads the new line character left by input.nexInt() in the class method.

             if(choice < 1 || choice > 4)
                  System.out.print("\n\nPlease Enter a choice within (1-4) Range. Thank you.\n\n");                 

           }while(choice < 1 || choice > 4);


              switch(choice){

                 case 1:
                     customer[i].setService("Repair");
                     break;

                 case 2:
                     customer[i].setService("Repaint");
                     break;

                 case 3:
                     customer[i].setService("Wax & Polish");
                     break;

                 default:
                     customer[i].setService("Maintenance Service");

             }                                  
              do{                      
                  System.out.print("Enter a time for appointment (X:XX) Where X represents a digit along with a colon : ");

                  if(customer[i].getService().equalsIgnoreCase("Repair")){         

                      customer[i].setTime(input.nextLine()+"am");   

                      if (customer[i].getTime().matches("(9):[0-5][0-9]am"))
                            value = false;      
                      else{
                         value = true;
                         System.out.print("\n\nThis time is not available for this service. Please re-enter. Thank you.\n\n");
                      }      
                  }

                  else if(customer[i].getService().equalsIgnoreCase("Repaint")){

                      customer[i].setTime(input.nextLine()+"am");   

                      if (customer[i].getTime().matches("(11):[0-5][0-9]am"))
                            value = false;                          

                      else{
                         value = true;
                         System.out.print("\n\nThis time is not available for this service. Please re-enter. Thank you.\n\n");
                      }

                  }                      
                    else if(customer[i].getService().equalsIgnoreCase("Wax & Polish")){                          
                      customer[i].setTime(input.nextLine()+"am");                             
                      if (customer[i].getTime().matches("(1):[0-5][0-9]am"))
                            value = false;    
                      else{
                         value = true;
                         System.out.print("\n\nThis time is not available for this service. Please re-enter. Thank you.\n\n");
                      }                          
                  }
                    else {                          
                      customer[i].setTime(input.nextLine()+"am");   

                      if (customer[i].getTime().matches("(3):[0-5][0-9]am"))
                            value = false;    
                      else{
                         value = true;
                         System.out.print("\n\nThis time is not available for this service. Please re-enter. Thank you.\n\n");
                      }                          
                    }                                 
              } while(value);      
                  System.out.print("Enter a year : ");
                  year = handleEx.handle(input);                                                             

                  do{

                  System.out.print("Enter a month : ");

                  month = handleEx.handle(input);
                  month -= 1;                      

                  if(month < 1 || month > 12)
                          System.out.print("\n\nInvalid Date. Please re-enter. Thank you\n\n");                      
                  }while(month < 1 || month > 31);                  

                  do{                          
                      System.out.print("Enter a day : ");
                      day = handleEx.handle(input);
                      input.nextLine();

                      date.set(year, month, day);
                      value = handleEx.handle(date);                         

                  } while(value);                      

                  customer[i].setDay(Calendar.DAY_OF_MONTH + "-" + Calendar.MONTH + "-" + Calendar.YEAR);                                           

             do{                     
                 System.out.print("Please Enter Car Plate Number : ");                 
                 customer[i].setCarNo(input.nextLine().toUpperCase());                   
                 value = validation.validateCar(customer[i].getCarNo());                                                   
             }while(value);   

        string = input.nextLine();            

       i++;            

     } while(string.equalsIgnoreCase("Y"));

     try{

        file = new java.io.FileOutputStream("Appointments.bin" , true);
        object = new java.io.ObjectOutputStream(file);

        for(Customer s : customer)
            object.writeObject(s);

        file.close();
        object.close();
        System.out.print("\n\nRecord Successfully Stored!\n\n");            
    } catch(java.io.FileNotFoundException a){            
        System.out.print("Appointments.bin File Not Found , Please Contact The Developer to fix this issue. Thank you.\n\n");
        System.exit(-1);            
    } catch(java.io.IOException b){         
        System.out.print("IOException has occured. There might something wrong with the Appointmentss.bin file. Please Contact The Developer to fix this issue. Thank you.\n\n");

    }            
 }
 }

【问题讨论】:

  • CustomerRegistration 在哪里?好像不见了。
  • 已编辑.@kabanus
  • @kabanus 抱歉,做了一些改动。
  • 线程“main”java.lang.ClassCastException 中的异常:Assignment.Customer 无法转换为 [LAssignment.Customer;
  • 你没有听到别人告诉你的话。仅仅重复你所做的事情并不能说明你的理解。如果你不听而不听别人告诉你的话,在这里发帖就是浪费大家的时间。

标签: java serialization classcastexception


【解决方案1】:

您正在尝试将读取的单个 Customer 对象转换为 Customer 对象数组:aaa = (Customer[]) object2.readObject();

您可以从异常中读取: Assignment.Customer cannot be cast to [LAssignment.Customer。第一部分 (Assignment.Customer) 是虚拟机所拥有的,第二部分是它试图将其转换为的 ([LAssignment.Customer)。 [L部分是telling you it is an array of objects of a type的内部虚拟机方式。您不能将单个实例转换为数组。

Customer customer = (Customer)object2.readObject(); 可以在没有ClassCastException 的情况下工作。

在我的示例中,我假设最后写入文件的客户是null 引用。否则,您需要设计一种方法来知道何时停止阅读。

 List<Customer> customers = new ArrayList<>();
 try (ObjectInputStream object2 = new java.io.ObjectInputStream(new java.io.FileInputStream("Appointments.bin"));{
    Customer customer = (Customer)object2.readObject();

    while (customer != null) {
       customers.add(customer);
       customer = object2.readObject();
    }
 }
 customers.forEach(System.out::println);

【讨论】:

  • 但问题是我想从二进制文件中读取 Customer 类的对象数组。所以我可以打印存储在二进制文件中的每个数组。
  • 客户 customer = (Customer)object2.readObject();只读取 1 个数组元素。
  • 您需要在阅读时将阅读的客户添加到集合中。您还需要一种方法来知道何时停止阅读。我建议使用ArrayList&lt;Customer&gt; 而不是Customer[]。不幸的是,没有办法告诉虚拟机想要它不愿意提供的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
相关资源
最近更新 更多