Serialize an Object

have an Automotive class which has the following methods.
Iam able to read the i/p file and print the o/p in another file.
But when iam trying to serialize the Automotive class a .dat file is created but the o/p is not printed.
Can we do the serialize the Automotive object in the same class as i have done below??????????
Or should i create an instance of the class in the main() and then serialize()???
help required.
Here's the code below:
public class Automotive implements Serializable{
BufferedReader inputstream;
BufferedWriter outputstream;
StringTokenizer st;
OptionSet[] os= new OptionSet[50];//Instantiating OptionSet Class
private int coo[]=new int[50];//count of options
private String noo[]=new String[50];//array of options names
private int price[]=new int[50];//array of options price
private String type[]=new String[50];//array of option sets
private static final long serialVersionUID = 1L;
public void readFile()
try
inputstream = new BufferedReader(new FileReader("C:\\CarInputData.txt"));
outputstream = new BufferedWriter(new FileWriter("C:\\CarOutputData.txt"));
String line= inputstream.readLine();
st = new StringTokenizer(line,":");
outputstream.write("Car Model :" + st.nextToken());
outputstream.newLine();
inputstream.close();
outputstream.close();
}//end of try block
public void serializeAuto(Automotive a)
try
ObjectOutputStream output=new ObjectOutputStream(new FileOutputStream("C:\\CarData.dat"));
output.writeObject(a) ;
output.flush();
output.close();
public void deserializeAuto()
Automotive a;
try
ObjectInputStream input=new ObjectInputStream(new FileInputStream("C:\\CarData.dat"));
a = (Automotive) input.readObject();
}

I am confused by what you write. Serialized data is binary, not text:
import java.io.*;
public class SerExample implements Serializable {
    private String message;
    public void setMessage(String message) {
        this.message = message;
    public String getMessage() {
        return message;
    public String toString() {
        return getMessage();
    public static void main(String[] args) throws Exception {
        SerExample obj1 = new SerExample();
        obj1.setMessage("Hello, World!");
        File file = new File("temp.ser");
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
        out.writeObject(obj1);
        out.flush();
        out.close();
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        SerExample obj2 = (SerExample) in.readObject();
        in.close();
        System.out.println(obj2);
}Take a look at temp.ser after running this code.

Similar Messages

  • How to store a Non Serializable Java Object ?

    Hi..
    I have a non serializable java object which I want to store in the Oracle database and retrieve it. Can anyone help me with how to go about doing this ?
    many thanks in advance
    Ragavan

    If you share the same JVM then its possible, but I doubt that is the case. If you don't share the JVM then its
    impossible to share an object between two apps.
    But if all your attempting to do is duplicate the object in the other app then I spose it is possible, as long as
    you can reconstruct the object from information that you can interegate from the object.
    For example, if you have App A, and App B. WIthin App A is a Double d object. Then you could get the
    value of the Double by doing:
    d.doubleValue()
    write the double to a file/socket/stream, read the file/socket/stream at the other end, create a new Double
    via Double d = new Double(parsedValue);
    Now the two Apps will have a Double d object that represent the same value via a a.equals(b) == true, but
    they will not refer to the same object within memory/jvm.
    James.

  • Serialization by Object Type of IDOCS Out of XI

    Hi,
    I have the following scenario:
        File>XI>SAP DEBMAS IDOC(s)
    If an IDOC errors out (bad data sent in, customer locked etc.) it is going to create a work item on the receiving SAP system that will be reprocessed by a business user.
    The situation I want to prevent is this:
    IDOC 1 -
    Updates customer 100. 
    Changes the street to 222 Main St.
    This IDOC errors out because customer 100 is locked.  A work item gets created for reprocessing.
    IDOC 2 sent in before the work item is reprocessed -
    Updates customer 100.  Customer is no longer locked.
    Changes the street to 222 Main St South.
    Now the work item is reprocessed and the customer is updated to 222 Main St when it should be 222 Main St South.
    I think I can use serialization to prevent the second IDOC from being processed before the 1st IDOC is successfully processed.  However, I would like to allow an IDOC for customer 300 to be processed even if an IDOC for customer 100 is in error.
    Can I use Serialization By Object Type to accomplish this?(http://help.sap.com/saphelp_erp2004/helpdata/en/0b/2a66c9507d11d18ee90000e8366fc2/frameset.htm)
    Help.sap shows me how to set up the Serialization on the receiving SAP system.  However it states that the serialziation has to be set up on both systems.  Does this mean that I just do that same config on the XI system?  How does XI support the Serialization By Ojbects concept?
    Thanks,
    Jeff

    HI Jeff,
    My thoughts below....
    XI has to do the Job that would have been done by an SAP sending system...
    For instance, based on an object key some serialization numbers needs to be created & attached to the IDOC control record.
    I donot have access to a system right now...but one should be able to do this in many ways...
    One way i would do is like this...Enable serialization (say for customer master from the SAP system which i have access to)...Trigger some IDOCs making changes to different master records..see how the numbering is done by the SAP System and how it is attached to the IDOC(This is just to do a similar process as sap would do)....
    Once i see how SAP does it while sending the IDOCs, i will genearate a number on XI abap stack using a number range object & attach it to the IDOC as though it was done by the sending system...
    My 2 Cents...
    Thanks,
    Renjith.

  • Problem with Serializable JDO objects containing Hashtables

    Hi,
    I have a simple JDO object which contains a Hashtable and I would like to
    declare as Serializable. It seems though, that whenever I serialize this
    object, I get a NullPointerException. I've written a bare-bones test case
    and reproduced the exception, so I suspect this may be an enhancement issue.
    Thanks,
    Eric
    Exception in thread "main" javax.jdo.JDOException
    NestedThrowables:
    java.lang.NullPointerException
    at
    sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteC
    all.java:245)
    at
    sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:220)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:122)
    at
    org.jboss.ejb.plugins.jrmp.server.JRMPContainerInvoker_Stub.invoke(Unknown
    Source)
    at
    org.jboss.ejb.plugins.jrmp.interfaces.GenericProxy.invokeContainer(GenericPr
    oxy.java:357)
    at
    org.jboss.ejb.plugins.jrmp.interfaces.StatefulSessionProxy.invoke(StatefulSe
    ssionProxy.java:136)
    at $Proxy1.getHash(Unknown Source)
    at test.HashEjb.getHash(Unknown Source)
    at test.Test.doIt(Test.java:13)
    at test.Test.main(Test.java:7)

    Thanks for the prompt reply Patrick. I can hold off on this until early
    next week...
    "Patrick Linskey" <[email protected]> wrote:
    This is a confirmed bug. We do not correctly deserialize any proxy map
    classes.
    How soon is ASAP? None of us can work on it until later this evening at
    the earliest.
    -Patrick
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • Using database to serialize an object

    I am confused as to the simplest way to serialize an object (actually a simple JavaBean) to a database through jdbc. What classes do I extend and what methods do I overwrite? There are no transient data involved.

    If you expect to serialize a complex java object directly to a Relational database, it would not be possible. There are no data types which can directly hold 'objects'.
    If you want to serialize a java object, and want to store it as text in a database, it would be possible. For this you can serialize the object first to a file may be, and then copy the contents of file to the database text filed.
    although doing this, in my opinion, makes no sense.
    Usually when you are serializing object data to a relational database you first map the data to equivalant Relational data ... A table or few colums of a table may represent your object.

  • How to serialize a object to DataBase?

    A feasible way is that serialize the object to a file and then store this file to database. But I want to achieve it directly. How could I do?

         * Convert a serializable object to a byte array.
         * @param serializable Object to convert.
         * @return Byte array or null if failed.
         * @throws IOException on error.
        static public byte[] toByteArray(Serializable serializable) throws IOException {
            byte[] result = null;
            if (serializable != null) {
                ObjectOutputStream oos = null;
                try {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    oos = new ObjectOutputStream(baos);
                    oos.writeObject(serializable);
                    result = baos.toByteArray();
                } finally {
                    if (oos != null) {
                        oos.flush();
                        oos.close();
            }//else: input unavailbel
            return result;
        }//toByteArray()
    byte[] ba = toByteArray(mySerializableObject);
    ByteArrayInputStream bais = new ByteArrayInputStream(ba);
    preparedStatement.setBinaryStream("BINDATA", bais, ba.length)

  • How can I Serialize the Object of org.apache.xalan.transformer.TransformerI

    Teachers:
    How can I Serialize the Object of org.apache.xalan.transformer.TransformerImpl.

    org.apache.xalan.transformer.TransformerImpl doesn't appear to be serializable... what do you try to achieve?

  • Serialize the object between Server and Client?

    Hello friends,
    What is the important to Serialize the object between server and client?
    Thanks
    tamilvanan

    in which context ??
    Anyways,checkout the below link and try to understand how do we convert Serializable Object's State to in Stream and send it over network.
    http://java.sun.com/j2se/1.4.2/docs/guide/serialization/examples/index.html
    Hope that might help :)
    REGARDS,
    RaHuL

  • Serialize a object

    How can I serialize an object of a class that already implements the interface Iterator, can I make java implement more than one interface?
    Thanks

    yes.. seperate the interfaces with commas.

  • After serialize a object what will be the value of reference and primitive

    After serialize a particular object what will the value its object references and primitives ???
    please go through the following scenario
    import java.io.*;
    class Dog implements Serializable{
         String dogString = "haiHai";
         int dogSize = 555;
         public String toString(){
              return "This is Object Man";
    class MyTestSerial
         Dog d = new Dog();
         MyTestSerial(){
                   try{
                        System.out.println("Before Serialization Dog object is : " +d);
                        System.out.println("Before Serialization d.dogSize : " +d.dogSize);
                        FileOutputStream fis = new FileOutputStream("MyTest.ser");
                        ObjectOutputStream obs = new ObjectOutputStream(fis);
                        obs.writeObject(d);
    obs.writeInt(d.dogSize);
    obs.writeObject(d.dogString);
                        System.out.println("After Serialization Dog object is : " +d);
                        System.out.println("Before Serialization d.dogSize : " +d.dogSize);
                   }catch(Exception e){
                   System.out.println(e);
         public static void main(String[] args) { MyTestSerial t = new MyTestSerial();     }
    In the above MyTestSerial class am serializing Dog object. After executing this obs.writeObject(d); the dog object will serialize without any problem.
    Now, once i try to print the dog object and dogString it should print the null value right ??
    and its primitive dogSize in the Dog class also print the value zero right??
    But am not getting those results. What mistake am doing here???
    Generally What will happen when we serialize a object or primitive value. After this what is the value of these types??
    Can any one a give the solution???
    Regards
    Dhinesh Kumar R

    Serializing merely copies the object data to the stream, the content is unaffected.

  • Trying to serialize C# object and store as XML Datatype in Sql Server 2005

    using
    if (Obj != null)
                   MemoryStream stream = new MemoryStream();
                   StreamWriter writer = new StreamWriter(stream);
                   XmlSerializer x = new XmlSerializer(Obj.GetType());
                   x.Serialize(writer, Obj);
                   writer.Close();
                   byte[] arr = stream.GetBuffer();
                   return Encoding.UTF8.GetString(arr).Trim();
    The object looks like
        public class CorporateBondSec : BaseSecurity
            public double coupon; // CPN
            public string couponType; // CPN_TYPE
            public int couponFreq; // CPN_FREQ
            public string floater; // FLOATER
            public int resetFreq; //REFIX_FREQ
            public DateTime resetDate; //NXT_REFIX_DT              
            public DateTime firstCpnDate; //FIRST_CPN_DT
    XML looks like
    '<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<CorporateBondSec xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n  <coupon>8</coupon>\r\n  <couponType>FIXED</couponType>\r\n  <couponFreq>2</couponFreq>\r\n  <floater>N</floater>\r\n  <resetFreq>0</resetFreq>\r\n  <resetDate>0001-01-01T00:00:00</resetDate>\r\n  <firstCpnDate>0001-01-01T00:00:00</firstCpnDate>\r\n</CorporateBondSec>'
    Error from SQL
    Msg 9413, Level 16, State 1, Procedure procSecuritiesInsert, Line 0
    XML parsing: line 1, character 15, A string literal was expected
    I have also tried
    XmlSerializer x = new XmlSerializer(Obj.GetType());
    System.Text.StringBuilder builder = new System.Text.StringBuilder();
    x.Serialize(XmlWriter.Create(builder), Obj);
    return builder.ToString();
    That gives me an XML
    '<?xml version=\"1.0\" encoding=\"utf-16\"?>
    <CorporateBondSec xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
    <coupon>8</coupon>
    <couponType>FIXED</couponType>
    <couponFreq>2</couponFreq>
    <floater>N</floater>
    <resetFreq>0</resetFreq>
    <resetDate>0001-01-01T00:00:00</resetDate>
    <firstCpnDate>0001-01-01T00:00:00</firstCpnDate>
    </CorporateBondSec>'
    Error
    Msg 9413, Level 16, State 1, Procedure procSecuritiesInsert, Line 0
    XML parsing: line 1, character 15, A string literal was expected

    Tony,
    this is how your XML should look like.
    Code Snippet
    '<?xml version="1.0" encoding="utf-16"?>
    <CorporateBondSec xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <coupon>8</coupon>
    <couponType>FIXED</couponType>
    <couponFreq>2</couponFreq>
    <floater>N</floater>
    <resetFreq>0</resetFreq>
    <resetDate>0001-01-01T00:00:00</resetDate>
    <firstCpnDate>0001-01-01T00:00:00</firstCpnDate>
    </CorporateBondSec>'
    I see you have a few extra '\' characters before double quotes. you need to remove them.

  • How to persist an entity with (any) Serializable Java Object as a field?

    Hello,
    I've understood, that in addition to basic and primary types, an entity bean can have basically any serializable object as its field. I just can't get it working. All I want, is just to have an entity bean with, for example, a HashMap or Properties as one of the its fields. And afterwards, when I'd query the bean again from the persistent storage, it would have the HashMap or Properties fields set just as they were while persisting the bean. So the basic functionality.
    So far, the only way I've gotten this working, is by defining the field as byte[] and then by using ObjectInput/OutputStreams and ByteArrayInput/OutputStreams I can read/write my HashMap or Properties as a byte[] and persist the entity... Not very clever, is it :)
    I've tried to annotate the field with @Lob but it eventually ends up with casting problems when fetching the data from the persistent storage, because TopLink gets a blob, a byte array from the persistent storage and doesn't know how to convert it into HashMap or Properties like I want it to.
    This was close to mine, but still didn't get it working..
    http://forum.java.sun.com/thread.jspa?threadID=749447&messageID=4287919
    ps. Working with AS PE9, MySQL and PostgreSQL..
    Best regards,
    Samuli

    Hello,
    Sorry, I'm not sure what you mean. The ID used for the entity does not need to match the actual database constraints, so you can use any mapping in the entity as the ID as long as its value will be unique. If it is not unique, you will run into problems when EclipseLink thinks the entity already exists, performing an update instead of an insert.
    Can you describe the performance problems you are having, and what type of sequencing you are using? It is possible to improve performance using batch writing and sequence pre-allocation.
    See http://wiki.eclipse.org/Optimizing_the_EclipseLink_Application_(ELUG)#How_to_Use_Batch_Writing_for_Optimization
    and http://wiki.eclipse.org/Optimizing_the_EclipseLink_Application_(ELUG)#Table_11-11 for some of the options available.
    Best Regards,
    Chris

  • Send a Serializable java object as a payload in SOAPMessage

    Hi,
    I want to send any kind of java object (Serializable) as payload in SOAPMessage.
    I need the best solution to achive this.
    Regards,
    Riyaz..

    Lenine,
    Pardon me if I am stating the obvious here, but since you are talking about a java stored procedure, then you can use the "internal driver" to connect to the database. Have you read the relevant section of the documentation?
    (Note: Since I saw no details in your post regarding the Oracle version you are using, I have assumed the latest version, hence the above link.)
    Good Luck,
    Avi.

  • Serialization class object

    Whenever an object is to be sent over the network, objects need to be serialized.
    I am a learner.
    I would like to ask a question.
    If we implement the serialization for a class.
    In other class if we create a object of the above class.. Will it automatically serialized.??
    will that object called as serialized object??

    How to store serializable object in to a file.?ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
    out.writeObject(object);
    out.close();
    How to deserialize it in another class??You will be amazed at this, but:
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    Object object = in.readObject();
    in.close();
    // then you cast it to the expected type.
    This is all in the Javadoc.

  • Serialization big object(100k--2M) into MYSQL database

    Hi all !
    I have a big object need to be persisted into MYSQL database in my application.
    I use two method to meet this request
    1 ---- the object implement interface Serializable, but there is serializationVersionID is not same Exception
    sometimes.
    2 ---- Use XMLEncoder to save my object, the XMLEncoder generate the object XML text about 200k -- 3 M
    , but another problem occur :
    when I call flush method of XMLEncoder, my application will full ocuppy CPU time, and memory usage will increase to 90M, sometimes will ocurr "Not enough memory" Error.
    Why?
    can some one help me?
    Thanks in advanced

    1. You are modifying the signature of one or more of your classes that alters the (system generated) serializationVersionUID and then recompiling. You can declare this for yourself to get control to some extent. See the serialization spec for details.
    2. Your object graph is very large, which might be a problem using native or xml formats. Again, the specification details ways in which you can control the serialized form of your objects.
    On the information you've provided there's not much more that can be said.

Maybe you are looking for

  • Windows 7 client won't connect with 802.1x security

    Having issues connecting a windows 7 dell laptop with cisco unified wireless infrastructure.  Currently running 4 4402 WLCs and 1 wism.  The client in question is trying to connect to an AP that sits on one of the controllers on the wism.  WLC code r

  • How to set users from AD as UCM administrators

    Hi I need to set group from Active Directory as UCM administrators We have configured AD provider on WLS and group named MyGroup in AD I created role MyGroup in UCM and users from this AD group can login to UCM. I tried to create credentials map name

  • Mm-service entry sheet

    hi gurus, pls guide me in this issue While Creating Service Entry Sheet Error occured that Qty entered   exceeded by Qty in PO rgds

  • GlobeTrotter Connect failure with  Mac OS X 10.5.5

    I bought an AT & T USBCONNECT Quicksilver Data Card to use with the late 2008 MacBook Pro. The laptop has two partitions, one running Vista, the other Mac OS X 10.5.5 (forget version number, but whatever came with the laptop).The Data card works flaw

  • Remote Desktop/Access shared files over PPTP VPN

    Hello, I just bought the RV180W so I can connect to my office computer from anywhere as a VPN client. The two things I need to do while I am connected as a VPN client is to be able to access my files on my office desktop and be able to remote desktop