Object Serialization Question.

Hello, I'm working on a MUD client and I have a DataHolder class to store settings. I'm having problems getting the serialization process to work properly, could someone please give me an example of how to serialize this class and then restore it again? I would like to save the class as "prefs.ser" Here is an example class to use:
import java.awt.*;
import java.net.*;
import java.io.*;
public class DataHolder
     public Color foreground = Color.black;
     public Color background = Color.yellow;
// i dont want to save the socket info since it will change many times during actual operation
// also i know you have to catch the exception from the socket creation : )
     public transient Socket socket = new Socket("lordsoftherealm.org", 1234);
     public DataHolder()
     public setColors(Color foreground, Color background)
          // set background and foreground colors
          // the actual class include methods to retrieve colors, sockets, and other relevent data
          this.foreground = foreground;
          this.background = background;
     public Socket getSocket()
          return socket;
}Thank you for your time in helping me,
Joeyford1

Try this,
I am using this method to serializeand deserialize my objects ..
import java.util.Date;
import java.math.BigDecimal;
import java.io.*;
* This object compliments MyObjectTranslator and provides a method to translate
* any object into a type the database engine can process.
public class MyObjectTranslator {
public static Object translate(Object ob) {
if (ob == null ||
ob instanceof NullObject ||
ob instanceof String ||
ob instanceof BigDecimal ||
ob instanceof Date ||
ob instanceof ByteLongObject ||
ob instanceof Boolean) {
return ob;
else if (ob instanceof Serializable) {
return serialize(ob);
else {
// System.out.println("Ob is: (" + ob.getClass() + ") " + ob);
System.out.println("Unable to translate object. " +
"It is not a primitive type or serializable.");
* Serializes the Java object to a ByteLongObject.
public static ByteLongObject serialize(Object ob) {
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream ob_out = new ObjectOutputStream(bout);
ob_out.writeObject(ob);
ob_out.close();
return new ByteLongObject(bout.toByteArray());
catch (IOException e) {
System.out.println("Serialization error: " + e.getMessage());
* Deserializes a ByteLongObject to a Java object.
public static Object deserialize(ByteLongObject blob) {
if (blob == null) {
return null;
else {
try {
ByteArrayInputStream bin =
new ByteArrayInputStream(blob.getByteArray());
ObjectInputStream ob_in = new ObjectInputStream(bin);
Object ob = ob_in.readObject();
ob_in.close();
return ob;
catch (ClassNotFoundException e) {
System.out.println("Class not found: " + e.getMessage());
catch (IOException e) {
System.out.println("De-serialization error: " + e.getMessage());
so if you want it to translate it use it something like :
private Object translateObjectType(Object ob) {
return MyObjectTranslator.translate(ob);
and when you wana retrive it use it like :
Object ds = MyObjectTranslator .deserialize((ByteLongObject) ob);

Similar Messages

  • 2D objects Serialization problem

    Welcome!
    I'm making a net game using RMI and I have this problem.
    When I'm trying to join my client with the server an error occures:
    Error: error marshalling arguments; nested exception is:
         java.io.NotSerializableException: java.awt.geom.Ellipse2D$Double
    My client contains an Object extending a JPanel class. There are 2D object used to make the map, and that's why this error occures.
    It's a funny thing, cause I'm not sending a whole Object of my client, but only it's refference (using "this" in the join() method) so I dont know why does the 2D object need to be serialized and sent :|?
    Any way, my question is how to make 2D objects serializable!? I have jdk1.5.0_06 and as far as I remember they should be srializable in this version. Mabey I'm dooing something wrong!? Mabey it's nessesary to ad an appropreate code-line or import sth... i don't know
    please help me... I have little time to finish my project, and this thing is blocking my work.
    Big thanks to anybodey who will help.
    regards floW

    I'll tel u the whole story then, my problem is as follows:
    public class BounceThread{
       public static void main(String[] args)   {
          JFrame ramka = new BounceFrame();
             ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             ramka.setVisible(true);
    class BounceFrame extends JFrame{
    public BounceFrame()
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
          setTitle("MiniGolf v 1.0");
          panel = new BallPanel(); // this contains maps made with 2D objects
          panel.setBackground(Color.green);
          panel.setVisible(panel.czy_widać_panel());
          add(panel, BorderLayout.CENTER);
    // I add a menu bar, that starts a net game:
    JMenuBar pasekMenu = new JMenuBar();
              setJMenuBar(pasekMenu);
              JMenu menuGra = new JMenu("Game");
           // and so on... and finaly I add an option:
              menuGame_Nowa.add(new
                        AbstractAction("Net game")
                             public void actionPerformed(ActionEvent event)
                                  net_game(panel);
    // here i write my net_game method:
    public void net_game(BallPanel aPanel)
         //here, i make an Client object, and connect him with my server
         client = new mgClient(panel);
         client.join();
         // I give panel as a paramete, cause I cant think of another way of leting my server to uce it's (panels) methods
         // If I join only a name of my client, then how can I change the panel in my BounceFrame from the Clients method
         // "shouted" by the server!? It has to be a field in the client's object.
         // Is there any other way out!?
    // Class BouceFrame holds the panel as a field:
    private mgClient client;
    private BallPanel panel;
    //and so on...
    }and that's the real problem I'm facing here. Is there any solution!? I think, that making a Client's field out of my panel is the only way ot. And that means I need those 2D objects serialized... :(
    Please help if u can.
    Regards floW

  • Object serialization over an RS232 port

    Hi
    Thanks in advance for any help!!!
    I have just started embarking on a java project that incorporates both J2SE and J2ME technologies.
    In short:
    I am developing an embedded java system using a JStamp development kit. In conjunction to this I am also developing a java pc GUI application that is used for setting up a configuration for my embedded system.
    So here�s what I want to do.
    Firstly I would like to input a configuration via my java pc GUI application, and then once this configuration is complete I would like to wrap it in an object. Once the object has been created I would like to serialize it and send it over an Rs232 port as some kind of �OutputStream�. I would expect my embedded system to be listening to its serial port for this stream and then once received reconstruct the stream into it�s original object. The embedded system would then replace its current configuration with the new object.
    Questions:
    1.What kind of data streams and filtering streams will I need on the java pc application side (or how can I program these streams myself?)?
    2.How can I reconstruct this serialized object at the embedded system side

    From the javadoc:
    Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.
    This means ObjectOutputStream writes each Object instance once. It tracks instances which have been written and if they are written again, it only sends a "reference" to that object. This serves 2 purposes: 1) most importantly, preserves the integrity of the object graph and 2) reduces the amount of data.
    Two techniques to solve this:
    1) open a new stream each time
    2) use the reset method

  • Object serialization failure during OutOfMemory error (EOFException)

    Hello all,
    We are seeing a very strange situation when writing a serializable object to a flat file, specifically during an OutOfMemory condition. Our application saves the state of an object if an error occurs, and retries at a later point by reviving the object from its serialized form. We recently encountered a series of EOFExcetions when trying to reload the serialized object. Looking at the serialized data, we see that the file is indeed incomplete, and that it appears to be the serialized representation of the data contained within the object that is missing (the structure of the object appears to be stored in the serialized file, but not the runtime data).
    The code that produces and consumes these serialized objects is used in a variety of locations, and even in the case where these EOF errors occurred usually works as expected. The difference appears to be that the error condition which lead to the object serialization was in-fact an OutOfMemory error. That is, we had an OOM error elsewhere in our application, which caused our objects to be serialized to disk. During this serialization process we end up with corrupt (incomplete) serialization data.
    So.. the question is: Is it possible that the OutOfMemory situation causes the JVM to incorrectly serialize an object (without an error), and specifically to omit runtime data (variables) from the serialized form of the object?
    Thanks/

    jasonpolites wrote:
    So.. the question is: Is it possible that the OutOfMemory situation causes the JVM to incorrectly serialize an object (without an error), and specifically to omit runtime data (variables) from the serialized form of the object?you're sure that the serialization process completed without an error? how do you know the the OOME did not cause the serialization to fail (because the serialization process itself will require more memory, hence if it is happening while the system is near the memory peak, it is likely to fail as well)? generally, when a jvm starts throwing OOME's all bets are off. failures in random places can easily cause the whole internal state of a system to become invalid.

  • Docs about RowSet, and Object RowSet questions?

    Docs about RowSet, and Object RowSet questions?
    I can find RowSet forum, so I ask here!
    Can you give me URLs where I can find more about RowSet and URLs for any RowSet implementation?
    Does Borlans, Oracle, IBM, etc., have RowSet implementation?
    I find out about Sun's RowSet implementation, but I can't find Object Rowset in this implementation?
    Is it possible to develop Object RowSet and is it useful?
    I know about O/R tools like Hibernate, but Object RowSet can be useful?
    Run SQL query and get Objects, or maybe even run Object query (like EJB or Hibernate or JDO have) and get Objects.
    No XML mapping mess and simmilar, like with EJB or Hibernate or JDO?

    You can try
    http://java.sun.com/developer/Books/JDBCTutorial/chapter5.html
    This is a tutorail for RowSet

  • Servlet and Object Serialization

    Hi,
    I am developing a routing server in Java
    2 Instances of the same server will be running in 2 different data centers.
    The servers have a Jetty server embedded with a Servlet inside.
    Server 1 will use a GET method to talk to the Server 2 -> Servlet which will write the state of an object back which will read by Server 1 and reconstruct the object back.
    Do you find any issues in Object Serialization/DeSerialization in the Servlet.
    What are the factors that I need to consider in this case?
    Regards,
    Jana

    Make sure that your servlet handles the transaction in the same thread that doPost() or doGet() is called in.
    I ended up porting some old ServerSocket based code to a servlet, and was handing off the request and response objects to a handler thread on the server side. I ended up with a ton of intermittent errors like this.
    Once I started handling the transactions in the same thread things worked heartbreakingly well.

  • Customizing Forte object serialization

    Forte supports serialization of arbitrary object graphs into streams.
    However, there do not seem to be any well documented ways to customize
    this serialization, e.g. by using a different encoding scheme. It would
    seem there must be some support in there somewhere. I suppose at the
    very least, one could parse a serialized object (once one decoded the
    Forte encoding scheme) and do the conversion from that. That seems
    suboptimal, though.
    Has anyone done this? Any thoughts on how it might be done?
    Regards,
    Coty
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/forte>

    JavaFunda wrote:
    Object serialization is the process of saving an object's state to a sequence of bytes. Does it saves only the instance variable or also the object methods(like getter and setter methods) ? Only the state--the instance variables. It doesn't save the class definition. That has to be available separately (via classloader) at deserilaization time. In other words, you cannot deserialize an instance of a class that is not on your classpath.
    Once we we write the object to outputstream or some text file, how does it get transmitted over network?The same way any other bytes get transmitted. You have a Socket. You get its OutputStream. You wrap that in an ObjectOutputStream. When you write to the ObjectOutputStream, that writes through to the Socket's OutputStream, which is responsible for putting the bytes on the wire.
    Does we write the java object to text file only duuring serialization?We write the objects to wherever the other end of the ObjectOutputStream is connected to. Just like any other I/O.

  • Runtime Object serialization

    Hi,
    Could someone explain the concept of Runtime Object Serialization with a simple example?
    Thanks

    import java.io.*;
    /* you NEED to make the class implement Serializable */
    class Client implements Serializable {
        private String name;
        private String address;
        public String getName() { return name; }
        public String getAddress() { return address; }
        public void setName(String name) { this.name = name; }
        public void setAddress(String address) { this.address = address; }
        public String toString() { return "name='" + name + "' and address= " + address + "'"; }
    public class Test17 {
        public static void main(String[] args)  throws Exception {
            ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("test.bin"));
            Client myClient = new Client();
            myClient.setName("Steve Jobs");
            myClient.setAddress("1 Infinite Loop; Cupertino, CA 95014");
            System.out.println (myClient);
            oos.writeObject (myClient);
            oos.close();
            ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("test.bin"));
            Client yourClient = (Client) ois.readObject();
            System.out.println (yourClient);
    }Run the program above. It creates an object of the class "Client", serializes it into a file named "test.bin" and recreates the object reading it from the same file.
    Dumping the binary file you get this:
    0000    AC ED 00 05 73 72 00 06  43 6C 69 65 6E 74 F1 D7   ....sr..Client..
    0010    74 76 C4 64 FD 43 02 00  02 4C 00 07 61 64 64 72   tv.d.C...L..addr
    0020    65 73 73 74 00 12 4C 6A  61 76 61 2F 6C 61 6E 67   esst..Ljava/lang
    0030    2F 53 74 72 69 6E 67 3B  4C 00 04 6E 61 6D 65 71   /String;L..nameq
    0040    00 7E 00 01 78 70 74 00  24 31 20 49 6E 66 69 6E   .~..xpt.$1 Infin
    0050    69 74 65 20 4C 6F 6F 70  3B 20 43 75 70 65 72 74   ite Loop; Cupert
    0060    69 6E 6F 2C 20 43 41 20  39 35 30 31 34 74 00 0A   ino, CA 95014t..
    0070    53 74 65 76 65 20 4A 6F  62 73                     Steve JobsYou can see a lot of things in the serialization of the object Client - the name of the class is written, the names of the fields, the type (java/lang/String), and the values of the fields as UTF-8 encoded strings.

  • Object serializable?

    Hi,
    When writing a vector of my own objects out to a file, do the objects need to be serializable even though it is actually the vector I am outputting?
    Also, each of my objects in this vector have a field that is a vector of other objects...do I need to declare those objects serializable also?

    I think you still need to implement serializable on objects contained in the vector. I tried serializing a hashmap and my hashmap contained objects which needed to be serialized before the hashmap could be stored in a file.

  • SetAttribute() makes object serializable Recursively ?

              Hi everyone,
              could anyone answer me whether httpSession.setAttribute(key, very big object)
              makes the object serializable recursively.
              What I mean is, I am storing an object bigObject in http session using setAttribute().
              This bigObject contains several other objects which are not serialized.
              But I have read that setAttribute() makes the object serializable.
              So, does it mean that all the objects stored in bigObject also will be serialized
              thanks,
              jyothi
              

    But you can't serialize an Object that isn't Serializable somewhere in it's
              inheritance. A method can't make an Object Serializable.
              "jyothi" <[email protected]> wrote in message
              news:[email protected]...
              >
              > But i read clearly some where in bea online manual that use
              setAttribute() which
              > makes the object searializable. So I wonder whether this
              setAttribute() does
              > the searlization recursively ?
              >
              > thanks,
              > jyothi
              >
              > "justin" <[email protected]> wrote:
              > >
              > >Cluster requirement is that all objects placed in a session should be
              > >serializable.
              > >So your Big objects with small object which are not serializable is going
              > >to be
              > >a problem.
              > >
              > >"jyothi" <[email protected]> wrote:
              > >>
              > >>Hi everyone,
              > >>
              > >>could anyone answer me whether httpSession.setAttribute(key, very
              > >>big object)
              > >> makes the object serializable recursively.
              > >>
              > >>What I mean is, I am storing an object bigObject in http session using
              > >> setAttribute().
              > >> This bigObject contains several other objects which are not serialized.
              > >>
              > >>But I have read that setAttribute() makes the object serializable.
              > >>
              > >>So, does it mean that all the objects stored in bigObject also will
              > >>be serialized
              > >>?
              > >>
              > >>thanks,
              > >>jyothi
              > >
              >
              

  • Object serialization EOFException

    Essentially what I want to do is write to an object to a file. The program can terminate and then when I start the program again, it will read the object from the file and restore the program's original state before it was terminated.
    I get an EOFException with this code
    //insert code that gets input which will be stored in a hashtable
    //save Hashtable in "data.dat" using ObjectOutputStream
    //program terminates
    //program is re-ran again and checks for existing file
    File f = new File("data.dat");
    if(f.exists()){
           ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
           Object obj = ois.readObject(); //EOF exception occurs here
    }I know the above code works if I write the Hashtable and then read it back immediately without terminating in between. Am I missing something? Can object serialization be used in such a way that I can restore a program's original state before it was terminated?

    Sorry, I led you to believe that the actual class itself was going to be written to a file. I meant to say that the Hashtable in the class should be written to a file and then later on when I start the program again, it will restore the Hashtable to it's original state.
    My writing coding is something like this:
    Hashtable accounts = new Hashtable();
    //do stuff to the hashtable
    FileOutputStream fos = new FileOutputStream("data.dat");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(accounts);
    //Program can be terminated from this point
    //there is no further oos.writeObject() if it wasn't terminated
    //immediately after the above writeObject() call
    //Program is ran again and at startup it checks for existing file
    File f = new File("data.dat");
    if(f.exists()){
    ObjectInputStream ois = new ObjectInputStream(new FileInpuStream(f));
    Object obj = obj.readObject(); //EOFException occurs here
    }Again those lines work perfectly fine if I do not terminate the program and I force it to check for an existing file. If I terminate, it's almost as if the program thinks there's nothing in "data.dat" eventhough it's obvious by my code that I did write something to "data.dat".

  • Serialization question: can't write an object

    this may be a simple question but I do need to find out what's wrong with the object I am trying to serialize:
    The method (included) I use to write object works fine for some simple objects but stops without giving any message for some complex objects. It stops at "out.writeObject(obj)". Is there any other exceptions need to be caught or something else. Thanks a lot.
    public void writeAnObject(Object obj) {
    ObjectOutputStream out = null;
    try {
    out = new ObjectOutputStream(new FileOutputStream("obj.saved"));
    out.writeObject(obj);
    out.close();
    } catch (FileNotFoundException e) {
    System.err.println("Caught FileNotFoundException");
    e.printStackTrace(System.err);
    } catch (IOException e) {
    System.err.println("Caught IOException ");
    e.printStackTrace(System.err);

    Ok, one last thing... don't know if it will make any differance but why not?! This is a class that I used successfully in several projects when serializising Collections to file:
    * @author Andrew
    * @version 1.0 (2000-11-24)
    public class PersistentStorage {
         // The objectoutputstream
         private ObjectOutputStream out;
         // The objectinputstream
         private ObjectInputStream in;
          * This method saves a collection persistent to specified file.
          * @param obj          The collection we want to save.
         public void saveCollection(Collection obj, String fileName)
              throws FileNotFoundException, IOException {
              // Create a objectoutputstream
              out = new ObjectOutputStream(new FileOutputStream(fileName));
              // Write the collection object to file
              out.writeObject(obj);
              // Close the objectoutputstream
              out.close();
          * This method read a collection object from specified file.
          * @return collection          The collection we have read.
         public Collection readCollection(String fileName)
              throws FileNotFoundException, IOException, ClassNotFoundException {
              // Create a objectinputstream
              in = new ObjectInputStream(new FileInputStream(fileName));
              // Asign the read object to a Collection "container"
              Collection collection = (Collection) in.readObject();
              // Close the objectinputstream
              in.close();
              return collection;
    }The differens is that I don't catch any exceptions in those method writing and reading objects. Only throw exceptions.
    Try it out and see if it helps... (last shot) ;)
    /Andrew

  • Simple serialization question with objects

    Hi, I'm really new to the whole concept of serialization and what I want to do is create a blackjack game that can have up to 4 people playing, connected to a server that will act as the dealer. I need to be able to serialize some objects from the players to the server and have the server make some changes then send the objects back.
    However every example I've run across dealing with something of this nature involves writing to a file so I'm not sure what the code to do this would look like.
    My best guess would be ObjectInputStream and ObjectOutputStream but I don't understand how I can tell these streams that I just want to send the serialized object back and forth.
    If anyone could explain to me a bit better how these streams work, or show me roughly what the code might look like, I would really appreciate it.

    It doesn't matter whether you write to a file or a socket or a byte array or whatever. That stuff is what's under the ObjectOutputStream. When you create the OOS, you wrap it around some other stream (e.g. a FileOutputStream in the examples you're talking about I guess). To send something to a server, you'd instead just wrap it around the OutputStream of a Socket that's talking to that server. Everything else is the same.
    Whether you use raw sockets or some other means is up to you, but that's completely separate from the serialize/deserialize process.
    http://java.sun.com/docs/books/tutorial/essential/io/index.html
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • File Serializable question

    hi,
    i know i've seen plenty of posts asking how to transfer files, my question is why doesn't simplying sending a file object from the client to the server work, file just implement Serializable? is it because the contents don't travel with the object? i'm pretty sure the object will go across, via socket programming or rmi, but why not the contents, or will they?
    Thank you.

    Because the file object, to the best of my knowledge,
    does not hold the contents, it just contains
    information about the file, such as its path.Very true. I never thought about it in this depth before, but the [url http://java.sun.com/j2se/1.4.1/docs/api/java/io/File.html]API says:
    "An abstract representation of file and directory pathnames."
    That's all it is, a representation, not an actualy file.
    Cheers,
    Radish21

  • System and Object privileges question

    hello everyone.
    I was really making it a priority to really understand both system and object privileges for users. I have setup a couple of 'sandboxes' at home and have done lots of testing. So far, it has gone very well in helping me understand all the security involved with Oralce (which, IMHO, is flat out awesome!).
    Anyway, a couple of quick questions.
    As a normal user, what view can I use to see what permissions I have in general? what about permissions on other schemas?
    I know I can do a:
    select * from session_privs
    which lists my session privileges.
    What other views (are they views/data dictionary?) that I can use to see what I have? Since this is a normal user, they don't have access to any of the DBA_ views.
    I'll start here for now, but being able to see everything this user has, would be fantastic.
    Cheers,
    TCG

    Sorry. should have elaborated more.
    In SQLPLUS, (logged in while logged into my Linux OS), I am working to try and get sqlplus to display the results of my query so it is easy to read. Right now, it just displays using the first 1/4 or 1/3 of the monitor screen to the left. Make sense? So it does not stretch the results out to utilize the full screen. it is hard to break down and read the results because they are "stacked" on top of each other.
    Would be nice if I could adjust sqlplus so the results are easier to read.
    HTH.
    Jason

Maybe you are looking for