Help on serialization

pls how to serialize a static variable

OK, I was trying to be cute...
You don;t serialize variables per se, you serialize objects. See this:
http://java.sun.com/developer/technicalArticles/Programming/serialization/

Similar Messages

  • Help Needed: Serialization Problem

    I've got a problem with serialization, which is better illustrated with an example (slightly modified version of example in Tech Tips, February 29, 2000, Serialization in the Real World. The problem is that comparing serialized static final fields doesn't return correct result. Any help on how to fix this problem would be greatly appreciated. Thanks in advance. Here is the code:
    ====================
    import java.io.*;
    class Gender implements Serializable {
    String val;
    private Gender(String v) {
    val = v;
    public static final Gender male = new Gender("male");
    public static final Gender female = new Gender("female");
    public String toString() {
    return val;
    public class Person implements Serializable {
    public String firstName;
    public String lastName;
    private String password;
    transient Thread worker;
    public Gender gender;
    public Person(String firstName,
    String lastName,
    String password,
    Gender gender) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.password = password;
    this.gender = gender;
    public boolean isMale() {
    return gender == Gender.male;
    public boolean isFemale() {
    return gender == Gender.female;
    public String toString() {
    return new String(firstName + " " + lastName);
    public static void main(String [] args) {
    Person p = new Person("Fred", "Wesley", "cantguessthis", Gender.male);
    //-NOTE: there ia no problem with this check
    if (p.isMale()) {
    System.out.println("a male: " + p);
    } else if (p.isFemale()) {
    System.out.println("a female: " + p);
    } else System.out.println("strange");
    class WritePerson {
    public static void main(String [] args) {
    Person p = new Person("Fred", "Wesley", "cantguessthis", Gender.male);
    ObjectOutputStream oos = null;
    try {
    oos = new ObjectOutputStream(
    new FileOutputStream(
    "Person.ser"));
    oos.writeObject(p);
    catch (Exception e) {
    e.printStackTrace();
    finally {
    if (oos != null) {
    try {oos.flush();}
    catch (IOException ioe) {}
    try {oos.close();}
    catch (IOException ioe) {}
    class ReadPerson {
    public static void main(String [] args) {
    ObjectInputStream ois = null;
    try {
    ois = new ObjectInputStream(
    new FileInputStream(
    "Person.ser"));
    Person p = (Person)ois.readObject();
    //-NOTE: this is the problem: the check returns false
    if (p.isMale()) {
    System.out.println("a male: " + p);
    } else if (p.isFemale()) {
    System.out.println("a female " + p);
    } else System.out.println("strange");
    catch (Exception e) {
    e.printStackTrace();
    finally {
    if (ois != null) {
    try {ois.close();}
    catch (IOException ioe) {}
    }

    The Gender class implements a type-safe enumeration, but its implementation needs to be improved to ensure that re-creating a Gender object via deserialization doesn't create new objects but uses the existing objects. See this article for details on how that's done:
    http://developer.java.sun.com/developer/Books/shiftintojava/page1.html

  • Urgent deadline - Please help - Linux serialization problem

    Hi -
    I have a presentation on Wednesday morning of my program for my dissertation. I developed the whole thing in windows - it all works great... but the demo is on a Linux machine. Fortunately I tested today in Linux. I have a real problem. I want to save out a class instance. This code works fine in Windows:
                        String project_name = f.getAbsolutePath() + "/" + directory_name + ".oll";
                        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(project_name));
                        out.writeObject(mainCanvas);
                        out.flush();
                        out.close();The problem is that in Linux I just don't get anything saved. There is nothing there at all. No file is saved. I cannot work this out and am in a panic. Any help really appreciated.
    Olly

    Hi ,
    Please try to add this code to u'r prg.
    private void writeFile(String s, String s1)
    throws IOException
    Object obj = null;
    FileWriter filewriter = null;
    BufferedWriter bufferedwriter = null;
    if(sfmsDebug)
    System.out.println("Before Writing Received Messages To a File.");
    String s2 = System.getProperty("file.separator");
    if(System.getProperty("os.name").toUpperCase().indexOf("WIN") !=
    -1)
    File file = new File("c:" + s2 + s1);
    boolean flag = file.createNewFile();
    filewriter = new FileWriter("c:" + s2 + s1, true);
    bufferedwriter = new BufferedWriter(filewriter);
    } else
    File file1 = new File("/home/usr2/barcwas1" + s2 + s1);
    boolean flag1 = file1.createNewFile();
    filewriter = new FileWriter("/home/usr2/barcwas1" + s2 + s1, true);
    bufferedwriter = new BufferedWriter(filewriter);
    bufferedwriter.write(s, 0, s.length());
    bufferedwriter.write("\r\n");
    bufferedwriter.close();
    filewriter.close();
    if(sfmsDebug)
    System.out.println("After Writing Received Messages To a File.");
    }

  • Want help in Serialization

    Hi all,
    My requirement is there is a DTO object which i have. called Employee with many attributes like name, age , sex etc. Instead of storing each if the fields in different columns of the databse I wanna store it by serializing the object and persisting it in the databse. The column name type will have int. Is this possible. I have never known serialization. How do i do it. Is there any good tutorial for me to start of with serialization..
    This is an urgent requirement. What all do i need to know in order to persist the data and also I should be able to retrieve the column when queried and read the data.
    Regards,
    Hemanth

    Just make the class implement Serializable. However the column type will have to be Blob, not int.

  • Help reg. serialization compatibility

    Hi,
    We developed a web-application using J2SE 5.0. It runs in IBM Websphere 6.1(with IBM JRE 5.0). We have an applet for rendering our reports. The applet communicates with the web-application to obtain serialized form of the data that needs to be rendered in the applet. The browser in the customers' site runs jre 1.3.0 as they use other applications that depend upon it. Hence, we migrated the applet to run with jre1.3. This seems to work fine.
    My question is how does jre1.3 able to deserialize the data generated by IBM jre 1.5? Is this a mere coincidence? Are there any issues to be noted while deserializing the data generated by a newer version of jre, using an older version?
    The serialized data that I had mentioned is generated by a third-party library. Also, our applet is a wrapper around the third-party applet. So, I have no idea as to what kind of data is being exchanged between the servlet and the applet.
    Thanks in advance..

    The wire protocol for Serialization has not changed since Java 1.1 and the most of the base class library code that is serialization has serialversionUID set and is backward compatible. Therefore older version of JDK can communicate with newer version of the JDK. The only exception to this is Swing components - in the JavaDoc it has been documented that serialised Swing data is only suitable for short term storage or RMI between application.
    Most of the problem you would encounter with serialization between JDK release is actually in the application code. If you have forgot to set serialVersionUID then the JDK will generate one for you using the default field hashing algorithm in serialization library at runtime. This changes from release to release and therefore would break between the release. Therefore, always remember to put serialVersionUID in any classes that can be serialised in your application.

  • Help needed in a file to idoc scenario

    Hi all,
    The scenario is file to Idoc via XI. The problem here is the input file might contain both the PO create and PO change in the same file.
    Assume the first record is PO create and When we post this via XI there could be a delay for creating the PO in the SAP.
    Meanwhile even if the second record (say that's the PO change for the first PO create record) gets processed parallely there could be a possibility of error saying that PO is not created.
    How do we handle this in XI??.. If we use Queue Processing in IDoc adapter it'll guarantee only the delivery order and not the processing order if I'm right?.
    Please guide.

    Saravanan - IDoc preocessing can be handled by serialization. This will guarantee also the order of processing.
    <br/>
    <a href="http://help.sap.com/saphelp_nw04/helpdata/en/bd/277264c3ddd44ea429af5e7d2c6e69/frameset.htm" target="n">SAP Help - IDoc serialization in XI</a>
    <br/>
    <br/>
    Peter

  • IDOC Serialization issue.

    Hi,
    I tried to do IDOC serialization using this blog
    /people/community.user/blog/2006/11/04/how-to-serialize-idoc-xml-messages-fed-into-xi
    But in this blog its says to create a queue processing rule using WE85 transaction.
    My system is not as WAS 6.40, so when i tried to run WE85 transaction, it says transaction doesn't exist. SAP system is of enterprise version 4.7 (WAS 6.2)  and it doesn't have WE85.
    What is an alternative to this and how to achieve IDOC serialization.
    Thanks,
    Swapna

    Hi,
    http://help.sap.com/saphelp_nw04/helpdata/en/bd/277264c3ddd44ea429af5e7d2c6e69/content.htm
    The link above which has detail help on serialization.hope this helps.Pls check whether this helps.
    Regards,
    Sharath

  • How do I install Lightroom 6 and active it using serial number while I'm a Adobe CC subscriber?

    I'am a Adobe CC for photographer subscriber and I have activated the new Lightroom CC on my desktop computer and one of my laptops. Yesterday, I redeem a Lightroom 6 serial number from Leica product purchasing.
    When I install lightroom 6 on my another laptop, the installer asked me to login using my Adobe ID to which my subscription bundled. I could not find a place to input the serial number and after I logged in, it activated as Lightroom CC but not Lightroom 6.

    Does this help? Serialize Lightroom CC trial to activate as Lightroom 6

  • Question regarding ExternalizableLite

    One question regarding extending ExternalizableLite
    If I have a class A which extends ExternalizableLite as
    class A {
    int index;
    B objectB;
    I'd need to use the ExternalizableHelper's writeObject and readObject when deal with objectB member.
    If I also make class B extends ExternalizableLite, will that help on serialize/deserialize class A? Or it not going to help at all?
    Regards,
    Chen

    Hi Chen,
    if B is an ExternalizableLite implementor, then ExternalizableHelper.writeObject() will delegate to ExternalizableHelper.writeExternalizableLite(). I.e., it will write out a byte indicating that it is an externalizable lite, then writes out the classname and then delegates to your class B's writeExternal method. The improvement is the difference between the class B writeExternal method implementation and the Java serialization of the same class.
    If you know the type of the objectB member without writing the class name to the stream (e.g. if class B is final), then you can improve further by not delegating to writeObject, you can instead directly delegate to your class B's writeExternal method. Upon deserialization, you can instantiate the objectB member on your own, and delegate to the readExternal method of the newly instantiated objectB member.
    This allows you to spare the class name plus one byte in the serialized form of your A class.
    Best regards,
    Robert

  • Serializing text with component

    (Serializing text with component)
    The text is just ascii text, but it could be a considerable size (like 64k). The purpose would be to serialize, and then de-serialze all of this custom information I need for that component (and some other stuff). An example would be to save a list of names with my 'Name' component.
    I don't see any evidence that it is possible...
    Thanks,
    JR

    Well, imagine if we had to do serialization in this
    manner (i.e. manually). Not a pretty picture in my
    opnion...sure, that's why the API exists... don't take it the other way round and apply serialization to every single piece of data
    why do you think that serialization is easier btw ? here's the non-serialized version :
    Writer writer = new FileWriter(filename);
    writer.write(value); // I assume your text is available in a String named 'value'
    writer.close();and here it is with serialization :
    JButton container = new JButton(value);
    FileOutputStream fos = new FileOutputStream(filename);
    ObjectOutputStream outputStream = new ObjectOutputStream(fos);
    outputStream.writeObject(container);
    outputStream.close();Serialization helps you serialize complex objects (like graphical components) easily. It's a relatively heavy mechanism (compared to regular file writing) and shouldn't be used as a standard way of writing text to a file.

  • Serializing XMLDocument

    Has anyone run into problems serializing oracle.xml.parser.v2.XMLDocument and subsequently running XSLProcessor on it?
    My situation involves creating an XMLDocument object, sending it over an object stream from a server to a client, and then running it through the processXSL method of an XSLProcessor object.
    As a test, if I use processXSL on the server side before I send the XMLDocument to the client, it works fine. However, if I run it on the client side as soon as I receive the XMLDocument object, the process will produce what appears to be a malformed document.
    It's a bit extensive to provide and example, but I will try to get something together for the Oracle team.
    Thanks,
    Josh Peck
    [email protected]
    null

    Well, imagine if we had to do serialization in this
    manner (i.e. manually). Not a pretty picture in my
    opnion...sure, that's why the API exists... don't take it the other way round and apply serialization to every single piece of data
    why do you think that serialization is easier btw ? here's the non-serialized version :
    Writer writer = new FileWriter(filename);
    writer.write(value); // I assume your text is available in a String named 'value'
    writer.close();and here it is with serialization :
    JButton container = new JButton(value);
    FileOutputStream fos = new FileOutputStream(filename);
    ObjectOutputStream outputStream = new ObjectOutputStream(fos);
    outputStream.writeObject(container);
    outputStream.close();Serialization helps you serialize complex objects (like graphical components) easily. It's a relatively heavy mechanism (compared to regular file writing) and shouldn't be used as a standard way of writing text to a file.

  • Serializing: inserting and querying and de-serializing

    I need help storing serializable java classes into a table. I need working code to go both ways. How to get it in and how to get it out.
    I have a simple class that needs to stored in the DB. I first convert to bytes then store in a table. Getting it out is much harder. Help please
    null

    I need help storing serializable java classes into a table. I need working code to go both ways. How to get it in and how to get it out.
    I have a simple class that needs to stored in the DB. I first convert to bytes then store in a table. Getting it out is much harder. Help please
    null

  • Help on custom Serialization

    Hey all,
    I'm trying to design a networked whiteboard application and the thought I had was instead of trying to send a vector of the points the user has drawn, I send a BufferedImage with transparent background and the server simply draws each user's "layer" one on top of the other and distributes this to all clients. Obviously the problem here is that BufferedImage does not implement Serializable, and I don't have the knowledge to write custom serialization methods, can someone help me out?
    ~nill

    Convert the image to a byte array:
    Here is a small example...
         imageFile = new File("image.jpg");
         fis = new FileInputStream(imageFile);
         length = imageFile.length();
         if(length>Integer.MAX_VALUE)
              System.out.println("IMAGE FILE IS TOO LARGE");
         imageByteArray = new byte[(int)length];
         int offset=0;
         int numRead=0;
         while(offset<imageByteArray.length &&(numRead=fis.read(imageByteArray,offset, imageByteArray.length-offset))>=0)
              offset+=numRead;
         if(offset<imageByteArray.length)
              throw new IOException("Could not completely read file: "+imageFile.getName());
         fis.close();
    Hope that this helps..

  • HRMD_A IDoc Serialization Help

    Hi,
    I have a client that wants to activate IDoc serialization for HRMD_A. They have a global system that sends HR master data to multiple regional systems, MDM and SRM.
    The requirement is to serialize the IDocs for all regional systems, but not for MDM or SRM.
    My understanding is that we would need to activate both outbound and inbound serialization through SALE->Modelling and Implementing Business Processes->Configure Predefined ALE Business Processes->Human Resources->Master Data Distribution->Serialize HR Master Data.
    We would activate outbound in the global sending system, and inbound in each regional target system, but not in MDM or SRM.
    By activating serialization, will it activate for HRMD_A only, or for HRMDA_ABA as well?
    We would then need to make sure that the serialization counters are all initialized in both source and target systems. We can do this with transactions RE_RHALE_HRMDRGOUT and RE_RHALE_HRMDRGIN.
    Please correct me if any of the above is incorrect?
    Once serialization is activated, how will this effect the system? If for example an IDoc is sent with 100 objects, and one fails, then what status will the IDoc go into? Will all other objects process correctly? How would the error object affect subsequent IDocs?
    What steps need to be taken in order to resolve the following potential IDoc errors:
    - Change for person xxxxxxxx extends too far into past
    Delete IDoc? What to do with counters?
    - Object 01 ,z ,xxxxxxxx does not exist: infotype 1001 cannot be created.
    Resend missing objects with PFAL and then reprocess IDoc?
    - Relationship starting from 01 y xxxxxxxx impossible u2013 01 w zzzzzzzz does not exist/is not active.
    Resend missing objects with PFAL and then reprocess IDoc?
    - Personnel number xxxxxxxx is locked
    Will this sort itself out, or do we need to manually reprocess the Idoc?
    - Payroll area yy is locked for master data maintenance.
    Reprocess the IDoc after payroll areas is unlocked?
    Thanks very much for your help
    Edited by: David Bann on Sep 22, 2011 4:52 PM

    Hi,
    If change pointers are to be written for custom fields then the change document flag  at the domain level should be checked for that field. Then maintain an entry for this field in transaction BD52. Object name will be the same as the original fields. Changes to custom fields will be only picked if the change document for such fields is maintained in table BDCP.
    Try now!
    Reddy

  • Singleton serialization and weblogic - help!

    hi everyone,
    I'm trying to serialize a singleton cache object we're using for our (intranet)
    website running on weblogic 6.1. I've made sure the singleton class
    implements serializable, and i've also put the following method in the
    singleton class (ChartCache.java):
    private Object readResolve()
    return theInstance; //which is of type ChartCache
    By the way I'm using jdk 1.3. I've trawled the web and can't find anything to help me yet...
    Basically I've written a jsp to get the current instance of the cache
    and serialize it to a file. When I invoke another jsp i want it to
    reinflate the object and place it back into the weblogic jvm so it can
    once again be accessed as a singleton by all classes in the webapp. At
    the moment its just not working - the cache object will eventually
    take over half an hour to create (huge database processing going on)
    so I want the option, if weblogic falls over, to reinstantiate the
    cache without having to rebuild it from scratch. The cache will only
    be refreshed once a day.
    I'll c&p my jsp code below...
    ======================= restoreCache.jsp
    <%@ page import = "java.util.*" %>
    <%@ page import = "java.io.*" %>
    <%@ page import = "com.drkw.agencylending.website.chartcache.*" %>
    <%@ page import = "com.drkw.agencylending.log.Logger" %>
    <%
    ChartCache theCache = null;
    try
    String filename = "chartCache.dat";
    FileInputStream fis = new FileInputStream(filename);
    ObjectInputStream in = new ObjectInputStream(fis);
    theCache = (ChartCache)in.readObject();
    in.close();
    catch(Exception e)
    Logger.log(e);
    %>
    Resurrected chart cache from file.
    ======================= saveCache.jsp
    <%@ page import = "java.util.*" %>
    <%@ page import = "java.io.*" %>
    <%@ page import = "com.drkw.agencylending.website.chartcache.*" %>
    <%@ page import = "com.drkw.agencylending.log.Logger" %>
    <%
    ChartCache theCache = ChartCache.getInstance();
    String fileName = "chartCache.dat";
    try
    FileOutputStream fos = new FileOutputStream(fileName);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(theCache);
    oos.flush();
    oos.close();
    catch(Exception e)
    Logger.log(e);
    %>
    Wrote cache object to file.
    ============================
    At the moment, a file is getting written but it seems suspiciously
    small (73 bytes!) for what is a very large object. When I try to load
    it up again, I get no errors but when I call ChartCache.getInstance()
    (my singleton) it recreates the cache rather than using the one I've
    reinflated. BTW I don't need to worry about server clustering/JNDI to
    ensure I have a truly singleton instance - there will only ever be one
    JVM to worry about.
    Any help greatly appreciated!

    solved the problem using another technique. Rather
    than serialize the entire singleton object, I just
    serialized the hashmap (the only bit I really care
    about). Then in the private constructor, the class
    checks a database flag to see whether the singleton
    was created today - if not, I refresh the cache,
    otherwise load in the serialized hashmap and set that
    as my class member. No complicated jndi/ejb registry
    needed to get around it..!singleton serialization is not recommended in ejb enviroment, it will cause problems. in what you are doing, it is far better to persist the data values in a database.
    just for the sake of writing a serializable sington: in addition to what you do in a regular object, you would first check to see if this obj has been serialized, if it is, deserialize it and return this one. you would have to write your own method to do serialization, making sure you have only one place to serialize it, and let the object know where the file is.

Maybe you are looking for

  • A sparse image or sparse bundle question in relation to a NAS

    Hi all, I want to create a sparse image or bundle on my Synology DS713+ NAS to store my iPhoto and Aperture libraries. The reason for a sparse image or bundle lies in the fact that both iPhoto and Aperture very much like a solid Mac Journal formatted

  • Read XML file from different server on JSP

    Dear All, I am a newbie to JSP with XML, now i want to read the "test.xml" from JSP. I read successfully this "test.xml" file from my system and I got output, but I need to read the xml file from different server like "http://www.domain.com/test.xml"

  • MacBook Pro freezing with external monitor?

    I recently got an external monitor to use with my MBP (early 09). So it seems that if I have my monitor hooked up (and maybe also when my power cable is plugged in) and my computer goes into sleep mode, the whole thing freezes and i have to hard rest

  • Is it too much lines of code inside a class file?

    Hi, I was wondering about how many lines can be considered too much in a java class file. I saw some class files with more the two thousand lines of code and even more than three thousand lines. When we have so many lines in the code I've realized th

  • Automaticly run Program\Script After and MSI Installation

    Hi All, Today I started looking into the use of Application Model in SCCM 2012. It was easy to create an application by using the import MSI function, which automatically created the application, deployment type and detection rule. But I'm struggling