Search code examples
javaoopinheritancefile-handlingfilewriter

Can we read/write different type child classes of the same parent class to a textfile?


Suppose that I have an abstract class "Vehicle" and 2 other child classes inheriting from the Vehicle class called "Car" and "Bike".

So I can create a series of car and bike objects randomly:

Vehicle car = new Car();
Vehicle bike = new Bike();

And add them all to an Arraylist:

Arraylist<Vehicle> vehicles = new Arraylist<>();

Is it possible to write these objects to a single text file and also read it back from the text file to the Arraylist according to the specific object types(car, bike) without maintaining different textfiles for each type


Solution

  • If you want to store objects in a file, I'd advise you use object serialization. This link has useful details on how to serialise and deserialise a list

    This is how you serialize a list:

    ArrayList<Vehicle> vehicles= new ArrayList<>();
             
            vehicles.add(new Vehicle());
            vehicles.add(new Bike());
            vehicles.add(new Car());
     
            try
            {
                FileOutputStream fos = new FileOutputStream("vehiclesData");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(vehicles);
                oos.close();
                fos.close();
            } 
            catch (IOException ioe) 
            {
                ioe.printStackTrace();
            }
    

    To deserialize use the following:

    
            ArrayList<Vehicle> vehicles= new ArrayList<>();
             
            try
            {
                FileInputStream fis = new FileInputStream("vehiclesData");
                ObjectInputStream ois = new ObjectInputStream(fis);
     
                vehicles= (ArrayList) ois.readObject();
     
                ois.close();
                fis.close();
            } 
            catch (IOException ioe) 
            {
                ioe.printStackTrace();
                return;
            } 
            catch (ClassNotFoundException c) 
            {
                System.out.println("Class not found");
                c.printStackTrace();
                return;
            }
             
            //Verify list data
            for (Vehicle vehicle : vehicles) {
                System.out.println(vehicle);
            }
    

    Make sure all your classes implement serializable interface