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

    Default how to deserialize multiple objects in a file

    After much hair pulling and coffee I finally figured out how to serialize and deserialize objects. My issue is that it only adds one server object to my tree). Some info I have determined

    * 1 Server has 3 Targets and all 3 targets are added correctly so I'm assuming all objects are being written correctly, not overwriting the file, which means we can also assume all my Server objects are in the file.
    * readObject() uses a stack to deserialize since the last Server created&serialized was the first&only Server recreated/deserialized
    * I need a while(end of file !reached){server = nextReadObjcet(); add server} but there doesn't seem to be a way to iterate through using readObject()



    This is my first time using serialization and I know I can't be the only person with the absurd idea of wanting multiple instances of an objects deserialized so there has to be some basic method I'm missing or something.

    Oh BTW here is some code

    Server.java
    Java Code:
    	private static void save_object(Serializable object) throws IOException {
    	       ObjectOutputStream objstream = new ObjectOutputStream(new FileOutputStream(filename));
    	       objstream.writeObject(object);
    	       objstream.close();
    	}
    
    	public static Object load_object() throws Exception {
    	       ObjectInputStream objstream = new ObjectInputStream(new FileInputStream(filename));
    	       Object object = objstream.readObject();
    	       objstream.close();
    	       return object;
    	}
    	
    	public Server(String name) throws IOException   {
    		super(name);
    		//constructor stuff
    		save_object(this);
    	}
    Java Code:
    //while(){
    	serverGroup.addChild((Server) Server.load_object());	
    //}
    is there a way to work with that while loop to get each object in the file instead of just the last one?

  2. #2
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

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

    Default

    The while loop in that code doesn't iterate through(at least in my program it doesn't); instead it just keeps returning Orange. My updated code is here

    Java Code:
    	private static void save_object(Server object) throws IOException {
    	       ObjectOutputStream objstream = new ObjectOutputStream(new FileOutputStream(filename));
    	       System.out.println("Writing to file: "+object.getName());
    	       objstream.writeObject(object);
    	       objstream.flush();
    	       objstream.close();
    	}
    
    	public static Server load_object() throws Exception {
    	       ObjectInputStream objstream = new ObjectInputStream(new FileInputStream(filename));
    	       Server object = (Server) objstream.readObject();
    	       System.out.println("Reading from file: "+object.getName());
    	       objstream.close();
    	       return object;
    	}
    Java Code:
    	private TreeObject createServers(TreeParent nov) throws Exception{
    		Object obj = null;
    
    		while ((obj = Server.load_object()) != null) {
    			serverGroup.addChild((Server) Server.load_object());
    			System.out.println(ServerGroup.getChildren().length);
    		}
    
    		return nov;
    	}
    Whenever I run, it goes into an endless loop of reading in since read_object is never becomes null and my output is this.

    Reading from file: Orange
    Reading from file: Orange
    1
    Reading from file: Orange
    Reading from file: Orange
    2
    Reading from file: Orange
    Reading from file: Orange
    3
    ....

  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

    Perhaps I'm writing them in wrong? When I create the files I start with 3 servers and 3 targets per. It writes them all in correctly

    Writing to file: Westchase
    Writing to file: SHP
    Writing to file: Orange

    The file size is only 1kb which makes me think it's writing over the previous data so it only stores 1 object. Do you think this might be an issue why only 1 object is deserialized(even though it doesn't solve the issue of not reaching null and ending)?

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

    Default

    bump. This is the only thing stopping my project from being finished(and I'm oh so ready to be finished so I can relax the rest of the year)

  6. #6
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Question file postition?

    What is filename?
    Java Code:
    ObjectOutputStream objstream = new ObjectOutputStream(new FileOutputStream(filename));
    How is save_objectmade repetitive, recursive or "get next()" and possibly we need boolean append in the file constructor. What does
    Java Code:
    System.out.println("Writing to file: "+object.getName());
    print, show actual.What is
    Java Code:
    TreeObject
    ?
    Java Code:
    System.out.println(ServerGroup.getChildren().length);
    appears to be incrementing, looks to me like load_object() is opening the file from fpos (file position) == 0x0000 and thus reading the same file position (fpos) on each call.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

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

    Default

    fileName is the location of the .ser file containing the Server objects. It gets set using
    Java Code:
    //checks if server file exists then creates/writes to it
    		if(new File("C:\\Eclipse\\eclipse\\Servers.ser").exists() == false){
    			System.out.println("Server file DNE");
    			try {	
    				System.out.println("Writing servers");
    				writeServers();
    			} catch (IOException e1) {	e1.printStackTrace();	}
    		}		
    		else{
    			System.out.println("Server file exists");
    			serverFile = new File("C:\\Eclipse\\eclipse\\Servers.ser");
    
    		}
    save_object() works the same as overriding writeObject()(?)
    Java Code:
    	private static void save_object(Server object, File fileName) throws IOException {
    	       ObjectOutputStream objstream = new ObjectOutputStream(new FileOutputStream(fileName));
    	       System.out.println("Writing to file: "+object.getName());
    	       objstream.writeObject(object);
    	       objstream.close();
    	}
    The println statement in save_object() displays
    Java Code:
    Writing to file: Westchase
    Writing to file: SHP
    Writing to file: Orange
    TreeObject is the superclass to every object that can be attached to the TreeViewer.
    Java Code:
    public class TreeObject implements Serializable{
    	
    	private String name;
    	protected TreeParent parent;
    	private ListenerList listeners;
    
    
    	public TreeObject(String name) {
    		this.name = name;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setParent(TreeParent parent) {
    		this.parent = parent;
    	}
    	public TreeParent getParent(){
    		return parent;
    	}
    	public String toString() {
    		return getName();
    	}
    	public void addTreeObjectListener(ITreeObjectListener treeObjectListener) {
    		if (parent != null)
    			parent.addTreeObjectListener(treeObjectListener);
    		else {
    			if (listeners == null)
    				listeners = new ListenerList();
    			listeners.add(treeObjectListener);
    		}		
    	}
    }

    As for the println displaying the length of getChildren(); That was for determining that 1 Server(Orange) was being repetitively added. The Servers branch would show 1 Server leaf when there was a constantly increasing number of leaves showing up in the getChildren() method.

    Ideally getChildren() shows the number of nodes attached 1 level below Servers.

    I see what you mean about load_object() and now that you mentioned it I'm pretty sure that's what is happening.
    Java Code:
    	public static Server load_object() throws Exception {
    	       ObjectInputStream objstream = new ObjectInputStream(new FileInputStream(NavigationView.serverFile));
    	       Server object = (Server) objstream.readObject();
    	       System.out.println("Reading from file: "+object.getName());
    	       objstream.close();
    	       return object;
    	}
    I think the issue is that a new inputstream is declared for each object that gets deserialized. If that's the case then that is the reason why the .ser file contains only 1 line and from what I could tell(changing it to a .txt file) it only stores 1 object.

  8. #8
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Default

    Okay, work on the saveObject() loadObject() with detailed loop logic by pencil-paper + thinking type of reducto - I am sure this is likely to be the area as I have been through this too many times, that is usually where it is. The filename question really was a lead-in to the file.append() issue, it would have been followed by a detailed examination of the loop logic, how ReadObject works and needs to be done concurrently with the loop logic walkthrough. The question about the Tree was to see if in fact the read builds into a tree so that, ahem, losing the object in the forest ( no pun intended ) would be on the list of things to look at but it is likely the loop behaviour and the boolean FileAppend;

    save_object() works the same as overriding writeObject()(?) should not be an override, it should ( OO'ers help me with nomenclature ) utilize whatever in the base library does reading and writing of Objects.

    That has to be examined but it is likely the loop and the file read, we have to examine how readObject in the libs actually works and how it is intended to be used.

    Note for good practices, consider a large distributed traffic system where an inline piece of equipment takes incoming traffic that may have been on another physical hardware recently for transaction processing. It can become an issue of profound consequence in real world settings exactly what gets serialized and what gets ate up like cereal......
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

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

    Default

    I made a breakthrough but am still having issues. One problem was that I was creating a new outputstream each time I tried to write an object. I fixed this using
    Java Code:
    	private static void save_object(Environment object, File fileName) throws IOException {
    		if(fos == null){
    			fos = new FileOutputStream(fileName,true);
    		}
    		if(objstream == null){
    			objstream = new ObjectOutputStream(fos);	
    		}		
    	    System.out.println("Writing to file: "+object.getName());
    	    System.out.println("Writing using channel: "+fos.getChannel());
    	    objstream.writeObject(object);
    	    objstream.close();
    	}
    I'm curious as to why it will write 2 objects to the file but the 3rd one will throw an error. Below is the debug printlns with the stacktrace

    Java Code:
    Environment file DNE
    Writing environments
    Writing to file: Test1
    Writing using channel: sun.nio.ch.FileChannelImpl@9fe84e
    Writing to file: Test2
    Writing using channel: sun.nio.ch.FileChannelImpl@9fe84e
    java.io.IOException: The handle is invalid
    	at java.io.FileOutputStream.writeBytes(Native Method)
    	at java.io.FileOutputStream.write(Unknown Source)
    	at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
    	at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source)
    	at java.io.ObjectOutputStream.writeNonProxyDesc(Unknown Source)
    	at java.io.ObjectOutputStream.writeClassDesc(Unknown Source)
    	at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
    	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    	at java.io.ObjectOutputStream.writeFatalException(Unknown Source)
    	at java.io.ObjectOutputStream.writeObject(Unknown Source)
    	at groups.Environment.save_object(Environment.java:37)
    	at groups.Environment.<init>(Environment.java:58)
    	at views.NavigationView.writeEnvironments(NavigationView.java:658)
    	at views.NavigationView.createPartControl(NavigationView.java:219)
    	at org.eclipse.ui.internal.ViewReference.createPartHelper(ViewReference.java:371)
    	at org.eclipse.ui.internal.ViewReference.createPart(ViewReference.java:230)
    	at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:594)
    	at org.eclipse.ui.internal.WorkbenchPage$ActivationList.setActive(WorkbenchPage.java:4169)
    	at org.eclipse.ui.internal.WorkbenchPage$17.runWithException(WorkbenchPage.java:3234)
    	at org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
    	at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    	at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:133)
    	at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:3800)
    	at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3425)
    	at org.eclipse.ui.application.WorkbenchAdvisor.openWindows(WorkbenchAdvisor.java:803)
    	at org.eclipse.ui.internal.Workbench$27.runWithException(Workbench.java:1361)
    	at org.eclipse.ui.internal.StartupThreading$StartupRunnable.run(StartupThreading.java:31)
    	at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    	at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:133)
    	at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:3800)
    	at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3425)
    	at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2293)
    	at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2198)
    	at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:493)
    	at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:288)
    	at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:488)
    	at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    	at novlayout.Application.start(Application.java:21)
    	at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:193)
    	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:386)
    	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    	at java.lang.reflect.Method.invoke(Unknown Source)
    	at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
    	at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
    	at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
    	at org.eclipse.equinox.launcher.Main.main(Main.java:1212)
    Reading using channel: sun.nio.ch.FileChannelImpl@3a835d
    Reading from file: Test1
    I still wish there was a .next() method with inputstream that would add EVERY object in the file. Thats a problem I will get to after I can correctly write all objects.

    If needed here is my load_object method
    Java Code:
    	public static Environment load_object() throws Exception {
    		if(fis == null){
    			fis = new FileInputStream(NavigationView.environmentFile);	
    		}
    	    ObjectInputStream objstream = new ObjectInputStream(fis);
    	    System.out.println("Reading using channel: "+fis.getChannel());
    	    Environment object = (Environment) objstream.readObject();
    	    System.out.println("Reading from file: "+object.getName());
    	    objstream.close();
    	    return object;
    	}
    P.S. You were correct Nicholas about the fileName and making it appendable(is this even a word lol?). By simply changing my new File(String) to new File(String, true) it started adding each object to the nextLine. This also led me to discover FileChannel which I used to maintain 1 output stream so each object would be added to the file without having to create a new stream each time(also made sure it didn't override the previous object)
    Last edited by xcallmejudasx; 12-12-2008 at 12:17 AM.

  10. #10
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Talking Code Warrior in the making!

    gimme points, I actually do not care about them but I like your style so let's do it this time...you know appendectimize or something, wait till you see what I consider to be a variable name ~ ever heard of RandomX?

    for the next() what you do is write it yourself - that is not to be taken as flippant ( is that a word Flipper the Dolphin would object to ? ) be careful of things like FileChannel as they often work but have hidden gotcha's that will leave your project buried. Sue B. Good at Cuttham, Burnham and Runn originally wrote some ShellHooks to go fishing with. We see those as "Download Software Now" with nimwits in marching armies of soft crypto squashing and defeating all development with copious code bloat.

    Try my Boiler Room - pm me what you think. While you're at it, tell me why plural of Forum is "Forums" -> it is actually Fora, thus the plural of Algorithm would be .... what? Al Bundy goes Dancing of course.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

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

    Default

    RandomX the Mexican acid-metal band, the 24 year old Health Information Services Division Information Services Department IS Support Technician LANDesk Administrator(If your title alone is that long you HAVE to be important), or the method to generate a random integer?

    I really need to clear up some pre-conceived ideas I have about streams and properly working with them. Thinking about it now; it is extremely unrealistic to expect the same output stream to be used throughout the applications running life so dealing with the FileChannel should be left to the stream and not me. As long as each stream points to the same file they should work fine.

    I'm assuming the handler error resulted from trying to send multiple objects down the same channel. Sorta like sending 2 cars out the same exit but the first one stops at the exit which causes the second one to crash.(I'm picturing streams how I picture the cpu communicates with the north and southbridge, multiple threads sending bytes back and forth; never opposite directions within the same thread and never sending more data down a thread until the thread has been cleared and deemed ready for new data because the data can travel at different speeds)

    And the plural of Forum of Forums for the sheer fact that the English language is full exceptions and rules that make no sense. How is the plural of Moose Moose when the Plural of Goose is Geese? Or Mongoose is Mongooses?
    Colonel is pronounced Ker-nal. "I" before "E" except after "C" or if it's raining in Cuba and the moon is full ignore that rule unless your carrying an umbrella.

    I recently had a conversation with some Canadian friends of mine about this same thing. The result was the new English were too lazy to make up their own language so they used the old English language and just removed all "U"s from words like flavour, liqour, and swapped the "R" and "E" in words like theatre, litre(which they don't even use in their counting system) so they could claim it as their own.

  12. #12
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default hhhmmm ... plurals?

    If the plural of mouse is mice, then ...
    the plural of rat is rice? :)

    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

Similar Threads

  1. Replies: 2
    Last Post: 07-18-2008, 02:13 PM
  2. Can I store multiple objects in an array
    By lareauk in forum New To Java
    Replies: 9
    Last Post: 05-29-2008, 04:57 AM
  3. Can I use vectors to store multiple types of objects
    By Nathand in forum Advanced Java
    Replies: 6
    Last Post: 04-28-2008, 08:55 AM

Posting Permissions

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