Results 1 to 17 of 17
  1. #1
    JonoF is offline Member
    Join Date
    Apr 2009
    Posts
    13
    Rep Power
    0

    Default Using Scanner class to write to Vectors

    Right i've been messing around with this problem for a good few days, so i wonder if anyone here can help me out with it.

    I have a Vector full of Electrical Device objects which are series of classes created by myself with items such as TV's, Computers, Lights etc... each containing several methods and variables.

    I can save the vector to a .data file perfectly using the PrintWriter class but i'm stumped on how to use the Scanner file to read them back into the same vector (effectively a save/load function in my program).

    I've been trying along the lines of;

    Java Code:
    try
    {
            File electricDevicesFile = new File("electricDevices.data");
    	Scanner fileReader = new Scanner(electricDevicesFile);
    				
            while(fileReader.hasNext())
            {
               	electricDevices.addElement(fileReader.nextElectricDevice()); 
            }
            fileReader.close();
    }   
    catch (FileNotFoundException fnfe)
    {
    	JOptionPane.showMessageDialog(null, "File Not Found", "File Not Found", 0);
    }
    While i know full well nextElectricDevice() doesn't even exist, thats what i'm trying to get it to do. Get each electricDevices from file and add them to the vector one at a time.

    Any Ideas?

  2. #2
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    Have you looked into serialization. The readObject method (I'm assuming) works the same way that your nextElectricDevice method wants to work.

    By using writeObject and readObject you accomplish the same thing through a FileOutputStream and ObjectOutptuStream that you would by using PrintWriter and Scanner.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  3. #3
    JonoF is offline Member
    Join Date
    Apr 2009
    Posts
    13
    Rep Power
    0

    Default

    A friend from another forum recommended i use serialization, but when i looked into it, it all went a little over my head to be perfectly honest. :P

    And if you achieve the same thing by using writeObject and readObject that you do through using PrintWriter and Scanner, is there any advantages to doing it one way or the other? I'd rather use PrinterWriter and Scanner first so that i can use them effectively, but if there is another method that is drastically advantageous then i'll give it a bash. You got any examples i can adapt for this purpose?

  4. #4
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    Serialization is actually just fresh on my mind(I FINALLY got it working how i wanted it to after 3 months). As far as comparing the two, Serialization is faster(I believe not 100% positive) and simpler when re-creating your objects. Take my code for example

    Java Code:
    package serializeTest;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    public class SerializableObject implements Serializable   {
    
    	private static final long serialVersionUID = 1654834268554L;
    	static FileOutputStream fos;
    	static ObjectOutputStream oos;
    	private String name;
    	private int age;
    	static int count = 0;
    	
    	static{
    		try {	fos = new FileOutputStream("testSerialize.ser",true);
    		} catch (FileNotFoundException e) {	System.out.println("File not found exception");		}
    		
    		try {	oos = new ObjectOutputStream(fos);
    		} catch (IOException e) {	System.out.println("object stream error");	}
    	}
    	
    	public SerializableObject(){
    		this.name = "Steve";
    		this.age = 35;
    		count++;
    		
    		try {
    			oos.writeObject(this);
    			System.out.println("Object written");
    		} catch (IOException e) {
    			System.out.println("Error writing object");
    		}
    		
    	}
    	
    	public SerializableObject(String n, int a){
    		this.name = n;
    		this.age = a;
    		count++;
    		try {
    			oos.writeObject(this);
    			System.out.println("Object written");
    		} catch (IOException e) {
    			System.out.println("Error writing object");
    		}
    	}
    	
    	public void setName(String newName){
    		this.name = newName; 
    	}
    	
    	public void setAge(int newAge){
    		this.age = newAge;
    	}
    	
    	public String getName(){
    		return this.name;
    	}
    	
    	public int getAge(){
    		return this.age;
    	}
    
    }
    don't be overwhelmed most of this is just error catching. Look at my constructor. Using serialization you can write the entire object using writeObject and it will automatically put all the required attributes for recreation whereas with printwriter you would have to write(name), write(age), write(every single other attribute you have) so you can see where recreating the objects become a larger task when you have more complex objects.

    the FileOutputStream and ObjectOutputStream look very similar to the PrintWriter and they essentially work the same. You tell PrintWriter what file to write too but instead of writing the entire object you write all the attributes of the object.

    Serialization is guaranteed(99%) to work across systems regardless of the JVM and all these other factors, whereas say using printWriter and emailing the file to a friend to test could change the font type or indentations and what not which would mess with your scanner.

    Serialization comes highly recommended(at least from my boss and higher ups in this forum who recommended it to me) and at first it is really complicated to grasp but that's what we're all here to help you with. (It's cake once you understand though. I breathed a sigh of relief the first time it worked EXACTLY how I expected it too)
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  5. #5
    JonoF is offline Member
    Join Date
    Apr 2009
    Posts
    13
    Rep Power
    0

    Default

    Right i've given it a try, and it's compiles but because i've yet to sort out the load function i can't test it yet. Have a look because I'm abit iffy on why/how this works:

    Java Code:
    //Declaration of variables
    private static final long serialVersionUID = 1654834268554L;
    
    /*....
    Further down the code in my action listener
    ...*/
    
    try
    {
    	fos = new FileOutputStream("livingRoom.data", true);
    	oos = new ObjectOutputStream(fos);
    	oos.writeObject(electricDevices);
    }
    catch (FileNotFoundException fnfe)
    {
    	System.out.println("File not found exception");
    }
    catch (IOException e) 
    {	
    	System.out.println("object stream error");	
    }
    Is that it? Oh and does it matter what the serialVersionUID is?
    Last edited by JonoF; 04-15-2009 at 05:07 PM.

  6. #6
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    the serialVersionUID absolutely HAS to be there. But it really doesn't matter what it is.

    is myAppliances an array or what? There's a few ways you can go about saving the objects. You can either put the writeObject command inside your constructors or you can save all objects into an array and then just loop around the writeObject method. You only need to declare your fos and oos once for each class.

    the true parameter attached to your fos is set up to allow your file write new objects at the end of the file instead of writing over everything.

    You can test it by opening up livingRoom.data in a text editor. You should get something similar to

    Java Code:
     sr  serializeTest.SerializableObject  K	Š I ageL namet Ljava/lang/String;xp   #t test1sq ~     -t test2sq ~     7t test3sq ~     At test4sq ~     Kt test5  
    the first thing is your object type, the second and third thing are attributes and their data type, and all those test1sq test2sw etc are all the objects.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  7. #7
    JonoF is offline Member
    Join Date
    Apr 2009
    Posts
    13
    Rep Power
    0

    Default

    Right i get an IOException error when using the oos.writeObject(electricDevices).

    And when i open the file in notepad it looks nothing like what you put, maybe thats just because it's a vector rather than just a string and an int.
    Last edited by JonoF; 04-20-2009 at 06:09 AM.

  8. #8
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    your text file will probably look different because you're using a vector. It shouldn't be a problem writing it though since Vector is a subclass of Object.

    Try using the get method and adding each thing within the vector to writeObject instead of the entire thing.

    Something to pay attention too, in order for an object to be serialized its super class but also be serializable. When you goto serialize vector it has to serialze all objects within it also. To start off I'd recommend doing each device separately. This makes it a little easier when deserializing because when you would goto deserialize your vector it would have to deserialze every object reference inside of it.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  9. #9
    JonoF is offline Member
    Join Date
    Apr 2009
    Posts
    13
    Rep Power
    0

    Default

    Right...

    So the abstract Electrical Device class needs to implement serialization and given a serialVersionUID, and so do all it's sub-classes too?

    And this is going to be a fairly daft question, but how do i actually refer to exact objects in the vector? I know if it was an array it would just be arrayName[ theNumberYourAfter ], but as far as I'm aware it doesn't work the same way in vectors.

  10. #10
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    correct. ElectricalDevice and all subclasses need to implement Serializable and have their own unique serialVersionUID.

    vectorName.get(ii). It works like an ArrayList. You can use vectorName.maxCapacity (i think was the attribute it listed) for your loop limit. type javadocs into your web browser and take a peek at Vector for all the methods and stuff.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  11. #11
    JonoF is offline Member
    Join Date
    Apr 2009
    Posts
    13
    Rep Power
    0

    Default

    I think i could hug you now :D

    I think i've got it working, here's the code:

    Java Code:
    try
    {
    	int ii = 0;
    	for(int i = 0; i < electricDevises.capacity(); i++)
    	{
    		electricDevises.get(ii);
    		oos.writeObject(ii);
    	}
    }
    catch (IOException ioe) 
    {	
    	System.out.println("Error writing object");	
    }
    and what it outputs in the .data file when i have a single object in the vector is:

    Java Code:
     sr java.lang.Integer*‡8 I valuexr java.lang.Number†•”‹  xp    q ~ q ~ q ~ q ~ q ~ q ~ q ~ q ~ q ~
    which seems about right.

    Now how do i go about using the readObject class to load it back into the vector (the vector will be cleared of all components beforehand).

  12. #12
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    same way you saved everything really. Use FileInputStream and ObjectInputStream surrounded by a loop.

    Java Code:
    	private static void readObjects() {
    		SerializableObject obj = null;
    		
    		try {			fis = new FileInputStream("testSerialize.ser");
    		} catch (FileNotFoundException e) {	System.out.println("Error extracting file");	}
    		
    		try {			ois = new ObjectInputStream(fis);
    		} catch (IOException e) {		System.out.println("InputStream error");	}
    		
    		
    		try {
    			while((obj = (SerializableObject)ois.readObject()) != null){
    				System.out.println(obj.getName()+", "+obj.getAge());
    				array.add(obj);
    			}
    		} catch (EOFException e) {	
    			System.out.println("Reached end of file");
    		}catch (StreamCorruptedException e){
    			try {	fis.close();
    			} catch (IOException e2) {		System.out.println("Error closing stream");		}
    			try {	ois.close();
    			} catch (IOException e1) {	System.out.println("Error closing stream");		}
    		} catch (IOException e) {		e.printStackTrace();
    		} catch (ClassNotFoundException e) {	e.printStackTrace();
    		} 
    	}
    is the code to I use. take note that each time readObject is called, even if it's just to compare or check if it exists, the next time you call readObject it will pull the next object. Thats why my loop sets the variable the same time it compares.

    while((obj = (SerializableObject)ois.readObject()) != null)
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  13. #13
    JonoF is offline Member
    Join Date
    Apr 2009
    Posts
    13
    Rep Power
    0

    Default

    Humm... i've used your code and it works fine, until it hits the while loop, and which point it throws a ClassCastException. So somewhere i've tried to cast an integer to ElectricDevise.

    Java Code:
    int i = 0;
    
    while((obj = (ElectricDevise)ois.readObject()) != null)
    {
    	System.out.println(obj);
    	electricDevises.addElement(obj);
    	electricDevises.get(i);
    	imgLabel[i].setIcon(obj.getPicture());
    	i++;
    }
    I really can't work this one out, but it's definitely got something to do with that while loop because it doesn't even print obj to the command line before it throws the exception.

  14. #14
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    you're correct about the casting issue. Are you positive that every object your reading in is of type ElectricDevise and do you have a default constructor? If you're reading in different types you're going to need to have a switch statement that checks the type of object and then casts it.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  15. #15
    JonoF is offline Member
    Join Date
    Apr 2009
    Posts
    13
    Rep Power
    0

    Default

    Non of my objects are directly ElectricDevises, because my ElectricDevise class is abstract. But all the objects that are in the vector are objects that extend the ElectricDevise class. All these objects do indeed have default constructors aswel.

    In-case it's a problem with the way i'm adding them to the vector in the first place, here is an example of the code:

    Java Code:
    TV plasmaTV = new TV(); //creates new TV object
    electricDevise.addElement(plasmaTV); //adds object to next available space in electricDevise vector
    TV is one of the child classes of the ElectricDevise class.

    EDIT: Just thought of something, that section of code i just posted is part of a JButton which adds ElectricDevises to the vector. So if i add more than one TV to the vector, they will all have the name "plasmaTV" will this make a difference?
    Last edited by JonoF; 04-15-2009 at 10:37 PM.

  16. #16
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    I don't think the JButton should effect anything. I'm a little stumped. You could try to jimmy rig your objects with a getType method that like returns the name of the class and be like if
    (obj = (ElectricDevise)ois.readObject()).getType().equals IgnoreCase("TV")

    for every single type of device. Unless someone else has a better idea I'm stumped.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  17. #17
    Join Date
    Mar 2009
    Posts
    25
    Rep Power
    0

    Default

    Quote Originally Posted by JonoF View Post
    Non of my objects are directly ElectricDevises, because my ElectricDevise class is abstract. But all the objects that are in the vector are objects that extend the ElectricDevise class. All these objects do indeed have default constructors aswel.

    In-case it's a problem with the way i'm adding them to the vector in the first place, here is an example of the code:

    Java Code:
    TV plasmaTV = new TV(); //creates new TV object
    electricDevise.addElement(plasmaTV); //adds object to next available space in electricDevise vector
    TV is one of the child classes of the ElectricDevise class.

    EDIT: Just thought of something, that section of code i just posted is part of a JButton which adds ElectricDevises to the vector. So if i add more than one TV to the vector, they will all have the name "plasmaTV" will this make a difference?
    Maybe change this:
    Java Code:
    TV plasmaTV = new TV(); //creates new TV object
    electricDevise.addElement(plasmaTV); //adds object to next available space in electricDevise vector
    To this:
    Java Code:
    ElectricDevise plasmaTV = new TV(); //creates new TV object
    electricDevise.addElement(plasmaTV); //adds object to next available space in electricDevise vector
    Its a small change, just telling the compiler that they are ElectricDevise's and not the subclass directly.
    Last edited by hawaiian robots; 04-16-2009 at 03:49 AM.

Similar Threads

  1. Using the scanner class
    By danielwestjr in forum New To Java
    Replies: 1
    Last Post: 03-13-2009, 10:49 AM
  2. Scanner Class...
    By TheRocket in forum New To Java
    Replies: 5
    Last Post: 12-05-2008, 09:48 AM
  3. Vectors of Vectors or hash-somethings?
    By mindwarp in forum New To Java
    Replies: 3
    Last Post: 03-10-2008, 02:57 PM
  4. Scanner class
    By ajaymenon.k in forum Advanced Java
    Replies: 1
    Last Post: 11-26-2007, 07:01 AM
  5. JDK 5.0 Scanner Class
    By Sircedric88 in forum New To Java
    Replies: 3
    Last Post: 07-27-2007, 06:55 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •