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

Similar Messages

  • Can i write an Object back as an http response.

    can i write an Object back as an http response.
    my device will send an object to the servlet and in response i need to send an object. is this possible... can i write a sample program to simulate the device.

    Yes, though your object must be Serializable.
      public void doGet(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
              // code here for real work: Assume obj is the object you want to send back
            try {
                ObjectOutputStream oos =
                        new ObjectOutputStream(res.getOutputStream());
                oos.writeObject(obj);
                oos.close();
            } catch (IOException exc) {
                exc.printStackTrace();
    }

  • How can I write new objects to the existing file with already written objec

    Hi,
    I've got a problem in my app.
    Namely, my app stores data as objects written to the files. Everything is OK, when I write some data (objects of a class defined by me) to the file (by using writeObject method from ObjectOutputStream) and then I'm reading it sequencially by the corresponding readObject method (from ObjectInputStream).
    Problems start when I add new objects to the already existing file (to the end of this file). Then, when I'm trying to read newly written data, I get an exception:
    java.io.StreamCorruptedException
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    Is there any method to avoid corrupting the stream? Maybe it is a silly problem, but I really can't cope with it! How can I write new objects to the existing file with already written objects?
    If anyone of you know something about this issue, please help!
    Jai

    Here is a piece of sample codes. You can save the bytes read from the object by invoking save(byte[] b), and load the last inserted object by invoking load.
    * Created on 2004-12-23
    package com.cpic.msgbus.monitor.util.cachequeue;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    * @author elgs This is a very high performance implemention of Cache.
    public class StackCache implements Cache
        protected long             seed    = 0;
        protected RandomAccessFile raf;
        protected int              count;
        protected String           cacheDeviceName;
        protected Adapter          adapter;
        protected long             pointer = 0;
        protected File             f;
        public StackCache(String name) throws IOException
            cacheDeviceName = name;
            f = new File(Const.cacheHome + name);
            raf = new RandomAccessFile(f, "rw");
            if (raf.length() == 0)
                raf.writeLong(0L);
         * Whne the cache file is getting large in size and may there be fragments,
         * we should do a shrink.
        public synchronized void shrink() throws IOException
            int BUF = 8192;
            long pointer = getPointer();
            long size = pointer + 4;
            File temp = new File(Const.cacheHome + getCacheDeviceName() + ".shrink");
            FileInputStream in = new FileInputStream(f);
            FileOutputStream out = new FileOutputStream(temp);
            byte[] buf = new byte[BUF];
            long runs = size / BUF;
            int mode = (int) size % BUF;
            for (long l = 0; l < runs; ++l)
                in.read(buf);
                out.write(buf);
            in.read(buf, 0, mode);
            out.write(buf, 0, mode);
            out.flush();
            out.close();
            in.close();
            raf.close();
            f.delete();
            temp.renameTo(f);
            raf = new RandomAccessFile(f, "rw");
        private synchronized long getPointer() throws IOException
            long l = raf.getFilePointer();
            raf.seek(0);
            long pointer = raf.readLong();
            raf.seek(l);
            return pointer < 8 ? 4 : pointer;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#load()
        public synchronized byte[] load() throws IOException
            pointer = getPointer();
            if (pointer < 8)
                return null;
            raf.seek(pointer);
            int length = raf.readInt();
            pointer = pointer - length - 4;
            raf.seek(0);
            raf.writeLong(pointer);
            byte[] b = new byte[length];
            raf.seek(pointer + 4);
            raf.read(b);
            --count;
            return b;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#save(byte[])
        public synchronized void save(byte[] b) throws IOException
            pointer = getPointer();
            int length = b.length;
            pointer += 4;
            raf.seek(pointer);
            raf.write(b);
            raf.writeInt(length);
            pointer = raf.getFilePointer() - 4;
            raf.seek(0);
            raf.writeLong(pointer);
            ++count;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#getCachedObjectsCount()
        public synchronized int getCachedObjectsCount()
            return count;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#getCacheDeviceName()
        public String getCacheDeviceName()
            return cacheDeviceName;
    }

  • Can we write client object model code with Server object model?

    Hi everyone,
    I have to create one timer job using client object model (C#) in Sharepoint 2010 template on feature activation. Is it possible to write the code of client object in sharepoint empty project to create timer job? If yes/no? then why?
    Thanks in advance!!!

    Hi ShindeK,
    Yes you can used CSOM in Sharepoint but Timer jobs run directly on the server. The Client Side Object Model is a wrapper that brokers its calls to the server via the built in web services that SharePoint provides.
    You will not get any performance gains in this scenario using CSOM. You should use the full server object model of SharePoint
    SharePoint 2010 also has three Client Object Models (Managed, Silverlight, JavaScript) which are meant to be used by code accessing SharePoint remotely.
    --You can also used powershell script in timer job
    Chekc the link which cann help you step by step CSOM in Sharepoint timer job
    http://www.youtube.com/watch?v=Z7wHj-bSk0g
    You can also try the below link....
    https://bramdejager.wordpress.com/2013/08/02/using-csom-and-powershell-to-query-sharepoint-online-or-on-premise/
    http://stackoverflow.com/questions/3656920/run-sharepoint-timer-jobs-from-powershell
    Please mark the Answer and Vote me if you think that it will help you to resolved your issue

  • Newbie question: Can't get equal object widths

    I have two rectangle paths in my document. I don't remember exactly how I created them but as far as I can tell, they are very alike, same fill, no stroke. They are two vertical sides of a rectangular border around the perimiter of my doc.
    I would like to change the widths to be identical. Width/height proportion constraints are off. I enter the width of one object in the width field of the other, and the width changes but to some unpredictable number. I can put in a new number again and the width changes to something new but not what I want. I have tried to use different units, same result. I have no problem changing the heights of the corresponding horizontal paths to be the numbers I want.
    There is one visible difference between the paths: When the troubling path is selected, the blue outline around it is wider than on the other paths.
    I ended up throwing away the trouble path and copying the good one as a work-around. But I'd like to know what's going on, I assume I'm missing something basic.
    Hope somebody can help.

    With the rectangle tool (hotkey: M)
    Hold [Alt] and click where you want your rectangle to be centered. A window will appear with the height and width options.
    If it's all symmetrical, I would then use the Reflect tool, or Rotate tool to make a copy, where I wanted. With either tool, hold [Alt] and click the point you wish to rotate around. Check the preview box to make sure you have the right outcome, and then select the Copy option to finalize.
    If you are selecting one rectangle at a time and entering the new width into the Transform Panel, I am unsure what is happening.
    (Note: Instead of increasing the width, in the transform panel, by replacing 128 px with 256 px ▬ you have the option to add to the original number,
    so it would look like this: 128+128 px [it also works for decreasing, with subtraction])
    To select and scale two objects, in place, at the same time:
    Object→ Transform→ Transform each

  • How can I write to a Siemens S7-300 PLC tag from OPC Server.vbai page by using a Knob object ?

    I am using NI OPC Server and I can read Siemens S7-300 PLC tags such as thermocouple values from the PLC. Additonally I can write manually a constant value to that tag by selecting it in the NI Distributed System Manager. And I can read the written value from NI Distributed System Manager or from NI OPC Server. But I can not write any value to the S7300 PLC tags such as by using a knob object at the NI Vision Builder AI Inpection (.vbai) page.
    Any help is welcomed. Thanks in advance.
    Attachments:
    manual_writing_to_plc.png ‏298 KB

    The tutorial at the following location explains how to use Vision Builder AI as a OPC server.
    https://decibel.ni.com/content/docs/DOC-18647
    http://www.ni.com/white-paper/13574/en
    To allow VBAI to connect to an OPC Server (i.e. act as an OPC client), you need to purchase and install the DSC Run-time System.
    Once installed, you can create an OPC I/O client using the Distributed System Manager, create variables bound to OPC tags, then create VBAI network variables that are bound to these variables.
    Another possible technical solution to connect to OPC Servers supporting Data Access 2.0 is to use the datasocket API in a Run LabVIEW step.
    http://forums.ni.com/t5/Machine-Vision/Read-and-Write-with-OPC-through-NI-Vision/m-p/2048278/highlig...
    Hope this helps.
    -Christophe

  • Noob question, can't rotate object clockwise. Please see the pictures below.

    Hello everybody!
    I'm stuck at rotating objects as I tried to follow a tutorial.
    I think the answer is very simple, but because of my weak English, i can't even figure it out how to search for it on Google. tio
    So my question is how to rotate objects like this:
    Instead of this (That's how i can only rotate this object.):
    Thanks in advance!

    zollre,
    - before the value gives you clockwise. Basically, rotate angles are counterclockwise (with an implied + before the value).
    -20 degrees corresponds to 340 degrees (almost a full round counterclockwise).

  • How can I write relative path in File, ImageIcon objects

    I have downloaded examples from
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/index.html
    but for some reason images are invisible until I write absolute paths?(I use windows) How can I write relative path in File, ImageIcon objects?

    Hello;
    I've found a lot of complaints about this through the Forte forum as well as on Dejanews. I'm just curious as to whether any of you ended up finding a solution to this problem.
    There was one posting about setting up the subdirectory as a URL rather than a String and then using that as the source of the ImageIcon ... but this didn't work for me.
    Any help whatsoever would be appreciated.
    Thanks!

  • I can't read a Object from file, Please help me

    i want to write a Object into File. this is code of Object
    class objStoreCus implements Comparable, Serializable
    String customerID = new String();
    String customerName = new String();
    String customerEmail = new String();
    objStoreCus(String cusID, String cusName, String cusEmail)
    customerID = cusID;
    customerName = cusName;
    customerEmail = cusEmail;
    objStoreCus(){}
    public int compareTo(Object o)
    objStoreCus oS = new objStoreCus();
    oS = (objStoreCus)o;
    return(customerEmail.compareTo(oS.customerEmail));
    private void writeObject(ObjectOutputStream s) throws IOException {
    s.defaultWriteObject();
    private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
    try
    s.defaultReadObject();
    }catch(IOException ie){throw new IOException();}
    catch(ClassNotFoundException cnt){throw new ClassNotFoundException();}
    And I was wrote above Object into File by this code :+
    FileOutputStream fos;
    ObjectOutputStream oos;
    FileInputStream fis;
    ObjectInputStream ois;
    public void writeObjToFile(objStoreCus obj)
    try
    fos = new FileOutputStream("Exrcise3.ex3", true);
    }catch(FileNotFoundException fnfe){}
    try
    oos = new ObjectOutputStream(fos);
    //ghi doi tuong vao file
    oos.writeObject(obj);
    //dong stream
    oos.close();
    fos.close();
    }catch(IOException ie){}
    But i can't read above Object from file. allway have a Exception occur "StreamCorruptedException".
    this is code read Object form file :
    *parameter is ArrayList will be store Object from file.
    public void readObjFromFile(ArrayList al)
    try
    fis = new FileInputStream("Exrcise3.ex3");
    }catch(FileNotFoundException fnfe){}
    try
    ois = new ObjectInputStream(fis);
    while(true)
    try
    objStoreCus osc = new objStoreCus();
    osc = (objStoreCus)ois.readObject();
    System.out.println(osc.customerEmail);
    }catch(Exception e)
    e.printStackTrace();
    //System.out.println();
    break;
    ois.close();
    fis.close();
    }catch(IOException ie){}
    }

    Problem lies in
    os = new FileOutputStream("Exrcise3.ex3", true);
    You are trying to append to that file, You should always use new file to serialize objects.
    os = new FileOutputStream("Exrcise3.ex3");
    Try with above line.

  • Can you write vertically in the cell of a table, can you write vertically in the cell of a table

    can you write vertically in the cell of a table, can you write vertical

    If you don't understand that my response was a smiling echo of the stammering question I really can't help you.
    I guess that my 36725 points prove that I may be helpful. It seems that at this time you don't really know what are helpful answers.
    Using spreadsheets since more than twenty years, I know that storing something in an auxiliary object floating upon a cell isn't a serious workaround to the asked question. We may be sure that more or less soon, the object will no longer be were it was supposed to be.
    At this time, if we want to put a vertical text in a cell it's safer to insert a character, a linefeed, a character, a linefeed … which, one more time is echoing the stammering question.
    Yvan KOENIG (VALLAURIS, France) vendredi 29 avril 2011 14:37:08
    Please :
    Search for questions similar to your own before submitting them to the community

  • Please help- How can I publish an object with irregular getter/setter metho

    I'm encountering a problem with weblogic 9.2 web service. Here it is the description:
    I have a java class which doesn't expose getter/setter method, Like this:
    public class MyEntityList
    implements Cloneable, Serializable
    private Map subEntityMap;
    public final Object[] toArray()
    return subEntityMap.values().toArray();
    public final Iterator subEntities()
    return subEntityMap.values().iterator();
    public final GFIBaseSubEntity getSubEntityByKey(String key)
    if(key == null)
    return null;
    else
    return (GFIBaseSubEntity)subEntityMap.get(key);
    public final void setSubEntity(GFIBaseSubEntity entity)
    subEntityMap.put(entity.getKey(), entity);
    When I publish this object out, the web service engine will not parse the value in this object for it hasn't getter methods. But I do need the value in it, and I can't change the class for it's from external system. Can I define my own serializer class to process the MyEntityListin weblogic 9 or 10? Or is there any way to process this case?
    Thanks in advance

    In 1.4 you have ImageIO available ... javax.imageio.ImageIO.write is the method to call.
    - David

  • Write the Object to FIle

    sir,
    whether is possible to write the Object by using the RandomAccessFile?

    You can write byte arrays in to RandomAccessFile. The
    first repliy states how to get an object serialized
    in to a byte array.
    But there is an issue. That is object serialization
    will produce data of different sizes even for the
    different objects of same classes. If you want fixed
    length records in your random access file you will
    have to either write your own code to conver
    attributes of the object in to records. or you can ad
    a padding to the serialized object data to supports
    any object smaller than record length.Well, ByteArrayOuputStream can be created with a "size", so as long as you do it this way you should not have to worry about padding it yourself, it should already be padded with null bytes. AFAIK, anyway.

  • Can you write an excel file on client machine instead of on the server

    I am trying to user cfSpreadSheet functon. The first question I have is, can you write the file on a client machine? I tried but they all end up on the server drive. Scecond question, is there a way to do row and column range formating in CF9.0? SpreadsheetFormatCellRange function is only available for ColdFusion server version 9.01.
    Thanks.

    To expand on Dan's answer: CF doesn't have any interaction with the client browser at all: client->server comms are handled by the client and the web server; the web server simply asks CF to provide the response data if the file requested is a CF file.  But even then all CF does is process the requested file and return data to the web server.
    Also, one of the restrictions of the HTTP protocol is that that there is *no* *way* that the server can write to the client machine.  All it can do is send data to the client agent (eg: a web browser) in response to the client agent requesting it.  Can you imagine the sort of security problems one would open one's self up to if a remote web server could write to your PC????
    Adam

  • How can I write to 4 different tables in database at the same time

    I have .mdb file which has 4 tables for each hardware, I have a labview main program which calls 4 sub programs for each hardware, all these 4 subprograms run parallely.
    One might finish one test early or late by milli seconds or seconds, the data has to be written to database file which has 4 tables inside.
    I am planning to open reference in main program and use the reference in sub programs, I will write to Table 1 for first sub program , table 2 for second sub program and so on,
    My question is can we write into one database file having 4 tables parallely/simulataneously? If no why?

    Try it.  It should work.  As long as you are opening the database once, and passing the reference around, I don't see how it would not work. 
    You may run into troubles if two subvi's are trying to write simultaneously.  If so, use semiphores to lock out the action until done. 
    Or you could use a producer consumer architecture where the producer would queue up the table name and data, and the consumer would write to the database.  The producer can be replicated in each subvi.  In other words, each subvi will contain its own enqueue code.  All subvi's and the consumer loop would have to run in parallel.
    - tbob
    Inventor of the WORM Global

  • How can i convert an object to stream of chars or bytes?

    how can i convert an object to stream of chars or bytes?

    One way is the serialization mechanism. There are examples and explanations of it in the Java tutorial: http://java.sun.com/docs/books/tutorial/essential/io/serialization.html

Maybe you are looking for

  • Installing Solaris 9 on an x86 platform with win98 and win2K

    Hi, There is a Pentium P4 (2.4 GHz) machine with a 40 GB hard disk... This has 1 primary partition and the remaining is the extended dos partition. In effect there are the following logical drives - C, D, E and F. These are FAT32 partitions and have

  • Error code 50, only downloaded half the film

    Symptoms The following alerts may appear when trying to download purchased content from the iTunes Store: "There was an error downloading your purchased music. An unknown error occurred (-50)." This can happen when the connection timeout occurs while

  • W2 process & Final Check for Terminated employee (Payroll)

    -- how to create a Final Check for Terminated Employee ? --- How are W2 processed? thanks

  • Using Time Machine to transfer files to new Mac

    I plan on upgrading to an iMac. Can I use Time Machine carry my fies an programs over to the new machine?

  • What this error report is saying

    Final Cut is crashing a mac mini randomly and here is the error report.  I am tring to find out what it is saying caused the problem.  Thanks! Interval Since Last Panic Report:  1105909 sec Panics Since Last Report:          1 Anonymous UUID: