Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Writing Java Objects to an XML file

Options
  • 05-10-2009 3:18pm
    #1
    Registered Users Posts: 357 ✭✭


    Hello I am having a bit of trouble writing an Object Car to an XML file

    It keeps giving me the following two errors
    java.lang.InstantiationException: StorageFiles.Car
    Continuing ...
    java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(Car);

    The code I am using to write to the xml file is
    import StorageFiles.*;
    import addFiles.*;
    import java.io.*;
    import java.beans.XMLEncoder;
    public class SaveCarObjects {
    
    public void saveCarFiles(Car c)
    {
    try{
    
    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("cars.xml")));
    encoder.writeObject(c);
    }
    catch(Exception e)
    {
    e.printStackTrace();
    }
    }
    
    }
    

    the add car method is as follows
    //the different values are taken in.....
    Person driver = new Person(personName,personAddress,vehicleReg,tag);
    Car newCar = new Car(vehicleReg,driver);
    SaveCarObjects ss = new SaveCarObjects();
    ss.saveCarFiles(newCar);
    
    //Have a couple of System.out.print s to see that the values are being taken in correctly to the newCar object which they seem to be as it is outputting what I enter correctly suing the getMthods in the Car and Person class files
    

    Can anyone tell me what I am doing wrong? I can post the code for the classes Car and Person if needs be . Both are implementing Serializable

    Oh and will it be possible to read the various Objects that I am trying to store in this file later into an array of Car


Comments

  • Registered Users Posts: 1,322 ✭✭✭Mad_Max


    Post the Car class


  • Registered Users Posts: 357 ✭✭apoch632


    Car
    public class Car extends VehicleType implements Serializable {
        
    public Car(String reg, Person per)
    {
       regPlate = reg;
       person = per;
    }
    
    
        
    }
    
    VehicleType
    import java.util.*;
    import java.io.*;
    public abstract class VehicleType implements Serializable{
    
        protected String regPlate;
        Person person;
        int[] date; //For the method when it goes throw the toll bridge
    
        public String getRegPlate()
        {
    	return regPlate;
        }
        public void setRegPlate(String regPlateTakenIn)
        {
    	regPlate = regPlateTakenIn;
        }
        public Person getPerson()
        {
            return person;
        }
        public void setPerson(Person p)
        {
            person = p;
        }
    
    Person
    public class Person implements Serializable{
    
        
        String name;
        String address;
        String carRegPlate;
    
            //Different PayementTypes
        NonRegisteredPayement nonPayement=null;
        TagPayement tagPayement=null;
        VideoPayement vidPayement=null;
    
    
        ///Constructor For Non Registered Payement
        public Person(String nam,String add,String carPlate,NonRegisteredPayement non)
        {
            nonPayement = non;
            name = nam;
            address = add;
            carRegPlate = carPlate;
    
        }
        public Person(String nam,String add,String carPlate,TagPayement tag)
        {
            tagPayement = tag;
            name = nam;
            address = add;
            carRegPlate = carPlate;
            
        }
        public Person(String nam,String add,String carPlate,VideoPayement vid)
        {
            vidPayement = vid;
            name = nam;
            address = add;
            carRegPlate = carPlate;
    
        }
    
        //Get and Set Methods
        public String getName()
        {
            return name;
        }
        public void setName(String s)
        {
            name = s;
        }
        public String getAddress()
        {
            return address;
        }
        public void setAddress(String s)
        {
            address = s;
        }
        public String getPlate()
        {
            return carRegPlate;
        }
        public void setPlate(String s)
        {
            carRegPlate = s;
        }
    
        public NonRegisteredPayement getNon()
        {
            return nonPayement;
        }
        public void setNon(NonRegisteredPayement non)
        {
            nonPayement = non;
        }
        public TagPayement getTag()
        {
            return tagPayement;
        }
        public void setTag(TagPayement t)
        {
            tagPayement = t;
        }
        public VideoPayement getVid()
        {
            return vidPayement;
        }
        public void setVid(VideoPayement vid)
        {
            vidPayement = vid;
        }
    }
    
    I have the various payement objects all serialized as well


  • Registered Users Posts: 357 ✭✭apoch632


    I've rewritten it to pass the object to a data file
    public void saveCarFiles(Car c)
        {
            ObjectOutputStream obj = null;
            
            try{
                obj = new ObjectOutputStream(new FileOutputStream("cars.dat",true));
                obj.writeObject(c);
                
            }
            catch(IOException e)
            {  
                e.printStackTrace();
            }
        }
    

    it will write one object to a file but not any more(I think!! the size of the .dat file is not increasing when I keep calling my addCar method)

    I just want it to write multiple car objects to a file and then to be able to read them back in from that file. how would I go about do that


  • Registered Users Posts: 357 ✭✭apoch632


    Okay I now have it writing multiple car objects to a .dat file. And it can append on more cars as the addcar method is called.

    I was just wondering how can i read these multiple objects and show up the output.
    It reads in the first one fine but after that it throws a file read error. Ideally I want it to iterate through till it comes to the last object in the file. how would I go about doing that.
    package ActionMethods;
    
    /**
     *
     * @author apoch632
     */
    import java.io.*;
    import StorageFiles.*;
    public class ReadCarObjects {
        private ObjectInputStream input;
        private static int i;
    
        public void openFile()
        {
            try {
                input = new ObjectInputStream(new FileInputStream( "cars.dat"));
            }
            catch(IOException ioException)
            {
                System.err.println("Error Opening File :");
            }
        }
        public void readCars()
        {
            
            Car c1;
            Car c2;
    
            System.out.println("Printing Car Record");
            try{
                
                while(true)
                {
                    c1 = (Car) input.readObject();
                    c2 = (Car) input.readObject();
                   
    
                    
                    System.out.println(c1.getPerson().getName());
                    System.out.println(c1.getPerson().getName());
                    System.out.println(c1.getPerson().getAddress());
                    System.out.println(c1.getPerson().getAccount().getAccBalance());
                    
                    System.out.println(c2.getRegPlate());
                    System.out.println(c2.getPerson().getName());
                    System.out.println(c2.getPerson().getAddress());
                    System.out.println(c2.getPerson().getAccount().getAccBalance());
    
    
                }
    
                
                
    
            }
            catch(EOFException endOfFileException)
            {
                return;
            }
            catch(ClassNotFoundException classNotFoundex)
            {
                System.err.println("Unable to create Object");
            }
            catch(IOException ioEx)
            {
                System.err.println("Error During File Read");
            }
    
        }
        }
    


  • Closed Accounts Posts: 12,382 ✭✭✭✭AARRRGH


    Is this a college project or a proper application you're trying to develop? If it's the latter, you can get object persistance using something like Versant's object database.


  • Advertisement
  • Registered Users Posts: 357 ✭✭apoch632


    College project


  • Registered Users Posts: 5,618 ✭✭✭Civilian_Target


    Ah, yeah, was going to say...
    Is there some way to do easy XML serialisation inside the provided SDK? Because I am not aware of one, for debugger logs I use reflection and for production I use XStream.


  • Registered Users Posts: 357 ✭✭apoch632


    I should perhaps ask for a title change. I just want to read multiple objects from a file now.

    I can read the first object stored in the file fine but cannot read the second or any subsequent ones


  • Registered Users Posts: 6,240 ✭✭✭hussey


    apoch632 wrote: »
    Hello I am having a bit of trouble writing an Object Car to an XML file

    It keeps giving me the following two errors
    java.lang.InstantiationException: StorageFiles.Car
    Continuing ...
    java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(Car);

    The code I am using to write to the xml file is

    Any object using XMLEncoder/decoder must have a non-argument constructor
    like new Car() etc
    ideally it will conform to java.beans standard ....

    some alternative can be apache digester http://commons.apache.org/digester/
    kinda like a mapping of xPath to teh get/set methods etc

    or else use the Car class in an array or List etc and use XMLEncoder etc


Advertisement