Java – Object Array – serializing and deserializing

Source: www.stackoverflow.com

I’m trying to figure out the way to serialize and deserialize my array with objects. I have some amount (let’s say it’s 10) of objects in my array and those objects have the following variables linked to them – name(string), age(int) and colour(string). Those objects are of 3 different classes – it can be some sort of animals, fruits etc. They are of course declared to be serialized.

My goal is to write the array to the binary file (I think I’ve done it already), then read it back and print the entire array down in the console. I thought it would be as easy as reading/writing it to the text file but I’m worried that my code is going to be duplicated that way and I’m looking for a more “normal” way to do it. Unfortunately, I’m stuck with reading/printing it back. My current code looks like this:

private static void saveAnimalPenBinary(Animal[] animals, File file) {
       try (ObjectOutputStream apboos = new ObjectOutputStream(new FileOutputStream(file))) {
         apboos.writeObject(animals);
       } catch (IOException ex) {
           System.err.println(ex);
       }
   }
   private static Animal[] readAnimalPenBinary(File file) {
       try (ObjectInputStream apbois = new ObjectInputStream(new FileInputStream(file))) {
           Animal[] animals1;
           animals1 = (Animal[]) apbois.readObject();
           return animals1;

       } catch(IOException ex){
           System.out.println(ex);
           return new Animal[0];

       } catch(ClassNotFoundException ex) {
           System.err.println(ex);
           return new Animal[0];
       }
   }

I think it is reading the table correctly (array.toString is showing all objects) but I have a problem with printing the values other than the class name (I’m forced to that inside the reading method). The ones declared in the classes are not recognised at all (Intellij isn’t helping). Maybe the entire concept is wrong, that’s why I’d like for someone to have a look and maybe offer an alternative to this spaghetti.

Read More Here, go to stackoverflow Author of this News
Author: DrAhzek

Leave a Reply

Your email address will not be published. Required fields are marked *