>

클래스에서 이진 파일로 객체를 썼습니다. 이제 원하는 것은 객체 배열을 다시 읽는 것입니다. 하지만 대신 오류가 발생했습니다.

내 문제는 파일을 "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");
    }            
 }
 }


  • 답변 # 1

    하나의 Customer 를 캐스팅하려고합니다.   Customer 의 배열로 읽은 객체  사물 : aaa = (Customer[]) object2.readObject(); .

    예외에서 읽을 수 있습니다 : 와이즈 비즈 . 첫 번째 부분 ( Assignment.Customer cannot be cast to [LAssignment.Customer )는 가상 머신이 가지고있는 것이고, 두 번째 부분은 가상 머신을 캐스팅하려고 한 것입니다 ( Assignment.Customer ). ). 와이즈 비즈  part는 유형의 객체 배열임을 알려주는 내부 가상 머신 방식입니다. 단일 인스턴스를 배열로 캐스트 할 수 없습니다.

    [LAssignment.Customer   [L 없이 작동합니다 .

    내 예제에서 파일에 마지막으로 작성된 고객은 Customer customer = (Customer)object2.readObject(); 라고 가정했습니다.  참고. 그렇지 않으면 읽을 시간을 알 수있는 방법을 고안해야합니다.

    ClassCastException
    
    
    null

  • 이전 prolog - if 문을 사용하는 방법 - 루프
  • 다음 MySQL에서 날짜 범위 쿼리 결과를 볼 수 없습니다