-2

I wrote an object from my class into a binary file now all I want is to read back into the object array. But I got an error instead.

My problem is I can't read the file into the object " aaa ". I want to read it to an array object called " aaa ". Below is the run time exception I got. But the code makes sense has no error. read.object returns an object class and all I did was cast it to (Customer[]). But I got this run time error below instead.

enter image description here

This is my code

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

My Human Class code

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

}

My customer class code

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";

}    
}

FullCode of Customer registrtion. Its not completed I was just testing around the read and write object function. So yeah some of them don't make sense and is unorganized.

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");

    }            
 }
 }
user207421
  • 305,947
  • 44
  • 307
  • 483
Cash-
  • 67
  • 1
  • 10
  • Where is `CustomerRegistration`? seems to be missing. – kabanus Jun 24 '18 at 12:12
  • Edited.@kabanus – Cash- Jun 24 '18 at 12:14
  • @kabanus Sorry, made a little changes. – Cash- Jun 24 '18 at 12:17
  • Exception in thread "main" java.lang.ClassCastException: Assignment.Customer cannot be cast to [LAssignment.Customer; – Cash- Jun 24 '18 at 12:17
  • Is what the error shows me. The code has no errors but it gives a runtime error above when I tried to read from the binary to the object array of class Customers – Cash- Jun 24 '18 at 12:18
  • Still a bit of a mess. Try and post the snippet relevant to the error separately, such that it is complete but minimal (so the part of the registration appears with relevant variable declarations, up until the failing line). – kabanus Jun 24 '18 at 12:21
  • You wrote a `Customer`. You're trying to read an array. It isn't an array. You can't read what you didn't write. Either write the array or read the objects one by one. Make up your mind. – user207421 Jun 24 '18 at 12:36
  • I wrote it to a binary file. I am trying to read it into a new object array of Customer. But I got the run time exception instead. – Cash- Jun 24 '18 at 12:45
  • You should also care about serialVersionUID when you serialilize/deserialize objects. – javamusings Jun 24 '18 at 13:40
  • You didn't write an array, so you can't read an array. Surely this is obvious? – user207421 Jun 24 '18 at 16:01
  • I wrote an object array. Why can't I read an object array. I changed my approach. I don't plan to store them anymore. I am using the inefficient way. Sadly I wanted to produce a perfect code for my assignment. No choice Its due in 3 days anyways. – Cash- Jun 24 '18 at 16:05
  • No, you wrote several objects in a loop. Not an array. You don't understand your own code. – user207421 Jun 24 '18 at 16:13
  • The code is not even completed. The reason I wrote several objects it allows the user to choose whether he wants to register another member. If he enter " Y " then it loops and the user is allowed to register and append into the binary file again. I din't include the message there. Like I said in the original post its not completed and some of them doesn't make sense its just a test for the objectinput and outputstream. But when I tried reading the binary file into the customer object it gives the run time error. – Cash- Jun 24 '18 at 16:32
  • Normally I organize my code and provide detailed question before posting here. Just was in a rush at the moment. Since stack overflow users is active and replies u in a few mins. So why not just throw it all here. – Cash- Jun 24 '18 at 16:33
  • I changed my approach anyways. Thank you guys! – Cash- Jun 24 '18 at 16:34
  • 1
    You are not listening to a word you are being told. Merely repeating what you did evinces no understanding. Posting here is a waste of everybody's time if you're not going to listen not what you're told. – user207421 Jun 24 '18 at 22:14

1 Answers1

0

You are trying to cast a single Customer object read into an array of Customer objects: aaa = (Customer[]) object2.readObject();.

You can read that from the exception: Assignment.Customer cannot be cast to [LAssignment.Customer. The first part (Assignment.Customer) is what the virtual machine has, the second part is what it tried to cast it to ([LAssignment.Customer). The [L part is the internal virtual machine way of telling you it is an array of objects of a type. You cannot cast a single instance into an array.

Customer customer = (Customer)object2.readObject(); would work without a ClassCastException.

In my example I assumed that the last customer written to the file is a null reference. Otherwise you need to devise a way to know when to stop reading.

 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);
M. le Rutte
  • 3,525
  • 3
  • 18
  • 31
  • But the problem is i want to read from the binary file into array of object of Customer class. So I can print each of the arrays stored in the binary file. – Cash- Jun 24 '18 at 12:27
  • Customer customer = (Customer)object2.readObject(); Only reads 1 array element. – Cash- Jun 24 '18 at 12:28
  • You need to add the customers you read to a collection while you are reading them. You also need a way to know when to stop reading. I'd advise to use a `ArrayList` instead of an `Customer[]`. Unfortunately there is no way to tell the virtual machine that want something of it that it is not willing to provide. – M. le Rutte Jun 24 '18 at 12:29