Reading in serialized objects in MIDP

I have a sudoku algorithm which generates a puzzle and then serializes the result and writes it out to a file using FileOutputStream and ObjectOutputStream. My question is how do i get this file read in J2ME, because i have another game which is on a mobile phone, programmed using J2ME, and as MIDP doesn't support serialization I am having problems getting it read in. And as we are here let me say this I am also havin problems understanding the RMS in terms of reading in a sudoku puzzle, could anyone please help me with the above issues, especially how record store system works when reading in a sudoku puzzle.

This has come up many times already:
Check this one:
http://java.sun.com/developer/J2METechTips/2002/tt0226.html#tip2
You should rewrite the server side like this as well, though.

Similar Messages

  • Writing and  Reading serialized Objects

    [code=java]
    /*hey guys i'm new to java and i have been given an exercise to make a cd collection, write it into a file and read the data back to the program.
    the program is suppose to show you a menu to select from where you can add, delete, view sort, CD's when you add a CD it must be written to a file as an Object and when you want to view CDs or search for a CD the program must read the CD objects from the file they have been written to and must return a cd nam, artist and release date. the code looks like it is writing the Cd to a file but when i try to read (view or search for a cd from the file it gives an error null). so i think i'm note reading the right way.
    thank you for helping .
    import java.io.Serializable;
    public class cd implements Serializable {
         //creating attributes
              private String cdname = null;
              private double price = 0.0;
              private String artist =null;
              private int ratings =0;
              private String genre=null;
              private String releaseDate =null;
         // creating an Empty constructor
              public cd(){
              public cd (String cdname,double price, int ratings, String genre, String artist, String releaseDate){
              this.cdname=cdname;
              this.price=price;
              this.artist=artist;
              this.ratings=ratings;
              this.genre=genre;
              this.releaseDate=releaseDate;
              public String getGenre(){
                   return genre;
              public void setGenre(String genre){
                   this.genre =genre;
              public String getArtist(){
                   return artist;
              public void setArtist(String artist){
                   this.artist=artist;
              public String getName(){
              return cdname;
              public void setName(String cdname){
              this.cdname = cdname;
              public Double getPrice(){
              return price;
              public void setPrice(double price){
              this.price = price;
              public String getReleaseDate(){
              return releaseDate;
              public void setReleaseDate(String releaseDate){
              this.releaseDate = releaseDate;
              public int getRatings(){
              return ratings;
              public void setRatings( int ratings){
              this.ratings = ratings;
    import java.util.*;
    public class hipHopCollection {
    ArrayList<cd> list = new ArrayList <cd> ();
    EasyIn ei = new EasyIn();
         private cd invoke;
         private int b;
         public void load()
              System.out.println(" You Entered " + b + " To Add A CD ");
              invoke = new cd();
              System.out.println("Please Enter A CD Name ");     
              invoke.setName(ei.readString());
              System.out.println("Please Enter A CD Price");
              invoke.setPrice(ei.readDouble());
              System.out.println("Please Give Ratings For The CD");
              invoke.setRatings(ei.readInt());
              System.out.println("Please Enter A CD release date ");
              invoke.setReleaseDate(ei.readString());
              System.out.println("Please Enter artist Name ");
              invoke.setArtist(ei.readString());
              System.out.println("Please Enter A CD Genre ");
              invoke.setGenre(ei.readString());
              list.add(invoke); // trying to add cd information to invoke.
         }// end of load
    // The following method should return the Object variable invoke that holds the cd INFO
         public Object getInvoke()
         return invoke;
         public int getB()
         return b;
         public void setB()
         b=ei.readInt();
         public void menu(){
              System.out.println("......................................................... ");
              System.out.println("Hi There Please Enter A Number For Your Choice");
              System.out.println(" Pess >>");
              System.out.println("1 >> Add A CD");
              System.out.println("2 >> View List Of CD's");
              System.out.println("3 >> Sort CD's By Price");
              System.out.println("4 >> Search CD By Name");
              System.out.println("5 >> Remove CD(s) By Name");
              System.out.println("0 >> Exit");
              System.out.println(".........................................................");
              System.out.print("Please Enter Chioce >> ");     
         }// end of menu
         public void GoodBye()
              System.out.println(" You Entered " + b + " To exit Good_bye" );
              System.exit(0);
         }//end of GoodBye
         public void PriceSort()
              System.out.println(" You Entered " + b + " To Sort CD(s) By price ");
              Collections.sort(list, new SortByPrice());
              for(cd s : list)
              System.out.println(s.getName() + ": " + s.getPrice());
         }// end of PriceSort
         public void NameSearch()
                   System.out.println(" You Entered " + b + " To Search CD(s) By Name ");
                   System.out.println("Please Enter The Name Of The CD You Are Searching For " );
                   String search = ei.readString();
                   for(int i=0; i<list.size();i++){
                   if(search.equalsIgnoreCase(list.get(i).getName() )){
                   System.out.println(list.get(i).getName() + " " + list.get(i).getPrice() + " " + list.get(i).getRatings() + " " + list.get(i).getGenre() );
    }//end of NameSearch
         public void ViewList()
                   System.out.println(" You Entered " + b + " To view CD(s) By Name ");
                   for(int i=0; i<list.size();i++)
                   System.out.println(list.get(i).getName() + " " + list.get(i).getPrice() + " " + list.get(i).getRatings() + " " + list.get(i).getGenre() );
         }// end of ViewList
         public void DeleteCd()
                   System.out.println(" You Entered " + b + " To Delete CD(s) By Name ");
                   System.out.println("Please Enter The Name Of The CD You Want to Delete ");
                   String search = ei.readString();
                   for(int i=0; i<list.size();i++)
                   if(search.equalsIgnoreCase(list.get(i).getName() ))
                   System.out.println(list.get(i).getName());
                   list.remove(i);
         }// end of DeleteCD
         public static void main(String[] args) {
         //creating an Instance of EasyIn by object ei. Easy in is a Scanner class for reading
              EasyIn ei = new EasyIn();
              ArrayList<cd> list = new ArrayList <cd> (); // creating an array cd list
              hipHopCollection call = new hipHopCollection();
              ReadWrite rw = new ReadWrite();
                   while (true){
                   call.menu();
                   call.setB();
                   //b = ei.readInt();
                   if(call.getB()==0)
                        call.GoodBye();
                   if(call.getB()==1)
                        call.load();
                        rw.doWriting();// trying to write the cd object to a file
                   if(call.getB()==2)
                   rw.doReading();// trying to read the cd object from a file
                   //call.ViewList();
                   if(call.getB()==3)
                   call.PriceSort();
                   if(call.getB()==4)
                        call.NameSearch();
                   if(call.getB()==5)
                        call.DeleteCd();
         }// end of while
    }// end of main
    }// end of class
    // importing all the packages that we will use
    import java.io.ObjectInputStream;
    import java.io.FileInputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.io.Serializable;
    public class ReadWrite {
    // these are all the attributes
         private String FileName ="CdCollections.dat";     
         private OutputStream output;
         private ObjectOutputStream oos;
         private FileOutputStream fos;
         private File file;
         private FileInputStream fis;
         private ObjectInputStream ois;
         //creating an empty constructor
         public ReadWrite()
         // we could initialise all the attributes inside this empty constructor
         //creating a constructor with arguments of a file name.
         public ReadWrite(File file)
              this.file=file;
              try
                   //Use a FileOutputStream to send data to a file called CdCollections.dat
                   fos = new FileOutputStream(file,true);
                   Use an ObjectOutputStream to send object data to the
                   FileOutputStream for writing to disk.
                   oos = new ObjectOutputStream (fos);
                   fis=new FileInputStream(file);
                   ois = new ObjectInputStream(fis);
              catch(FileNotFoundException e)
                   System.out.println("File Not Found");
              catch(IOException a)
                   System.out.println(a.getMessage());
                   System.out.println("Please check file permissions of if file is not corrupt");
         }// end of the second constructor
         //the following lines of code will be the accessors and mutators
         * @return the output
         public OutputStream getOutput() {
              return output;
         * @param output the output to set
         public void setOutput(OutputStream output) {
              this.output = output;
         * @return the objStream
         public ObjectOutputStream getOos() {
              return oos;
         * @param objStream the objStream to set
         public void setObjStream(ObjectOutputStream objStream) {
              this.oos = oos;
         public File getFile() {
              return file;
         public void setFile(File file) {
              this.file = file;
         public FileInputStream getFis() {
              return fis;
         public void setFis(FileInputStream fis) {
              this.fis = fis;
         public ObjectInputStream getOis() {
              return ois;
         public void setOis(ObjectInputStream ois) {
              this.ois = ois;
         // the following lines of code will be the methods for reading and writing
    the following method doWriting will write data from the hipHopCollections source code.
    that will be all the cd information.
    Pass our object to the ObjectOutputStream's
    writeObject() method to cause it to be written out
    to disk.
    obj_out.writeObject (myObject);
         public void doWriting()
              hipHopCollection call = new hipHopCollection();
    //creating an Object variable hold that will hold cd data from hipHopCollections invoke
              Object hold = call.getInvoke();// THI COULD BE THE PART WHERE I MADE A MISTAKE
              ReadWrite stream = new ReadWrite (new File(FileName));
              try
              Pass our object to the ObjectOutputStream's
              writeObject() method to cause it to be written out to disk.
              stream.getOos().writeObject(hold);
                   stream.getOos().writeObject(hold);
                   stream.getOos().close();
                   System.out.println("Done writing Object");
              catch (IOException e)
                   System.out.println(e.getMessage());
                   System.out.println("Program Failed To Write To The File");     
              finally
                   System.out.println("The program Has come To An End GoodBye");
         }// end of method DoWriting
    The following method is for reading data from the file written by the above method named
    DoWriting
    // PLEASE NOT THIS IS THE METHOD THAT GIVES ME NULL EXCEPTION
         public void doReading()
         ReadWrite read = new ReadWrite(new File(FileName));
              try{
                   //System.out.println("I AM NOW INSIDE THE TRY TO READ");
                   Object obj = read.getOis().readObject();
                   System.out.println("tried reading the object");
                   cd c = (cd)obj; // trying to cast the object back to cd type
                   System.out.println("I have typed cast the Object");               
                   System.out.println(c.getName());
                   System.out.println(c.getGenre());
                   System.out.println(c.getArtist());
                   System.out.println(c.getPrice());
                   System.out.println(c.getRatings());
                   System.out.println(c.getReleaseDate());
                   read.getOis().close();
              catch(ClassNotFoundException e)
              System.out.println(e.getMessage());
              System.out.println("THE CLASS COULD NOT BE FOUND");
              catch(IOException e)
              System.out.println(e.getMessage());// null
              System.out.println("WE COULD NOT READ THE DATA INSIDE THE FILE");
         }//end of method doReading
    }// end of class ReadWrite

    Cross posted
    http://www.java-forums.org/new-java/59965-writing-reading-serialized-java-object.html
    Moderator advice: Please read the announcement(s) at the top of the forum listings and the FAQ linked from every page. They are there for a purpose.
    Then edit your post and format the code correctly.
    db

  • Read a field of a serialized object

    Hi,
    is-it possible to read separately a field of a serialized object? By exemple, if I serialize an object that contains a String field, can I read only this String field?
    Thanks
    Jean

    You can do so, if you re-implement Java's serialization spec. That or overload readObject() and wait for your individual field to come in, trap the result and forward it on.
    As you can see from either of these alternatives, there is not a good way to do this. It's like asking 'how can I get an XML fragment from a file?" That task is, on the face of it, far easier. But it equally does not make sense.
    If you have control over the serialization, and you have a key lookup field, serialize it separately in an index-like file or serialize it ahead of Java's serialization in the same file.
    - Saish
    "My karma ran over your dogma." - Anon

  • FileUpload problem: InputStream does not contain a serialized object

    Hi All,
    I'm using the FileUpload component in a JSPDynPage and the htmlb component seems to work fine but I cannot read the file (InputStream). I get the following error(IOException): "InputStream does not contain a serialized object".
    Please let me know what is wrong with my code. This is a part of the code I used:
    public FileInputStream sourceFileInput;
    public ObjectInputStream input;
    FileUpload fu;
    fu = (FileUpload) this.getComponentByName("myFileUpload");
    IFileParam fileParam = ((FileUpload) getComponentByName("myFileUpload")).getFile();
    File f       = fileParam.getFile();
    file         = fu.getFile().getFile();
    absolutepath = fu.getFile().getFile().getAbsolutePath();
    this.sourceFileInput = new FileInputStream(file);
    input = new ObjectInputStream(sourceFileInput);
    The last line of code seems to generate te error.

    Hi,
    I have found the answers, thank you both.
    (I included the examle code. Perhaps of some use to someone.)
    FileUpload fu;
    fu = null;
    fu = (FileUpload) this.getComponentByName("myFileUpload");
    //       this is the temporary file
    if (fu != null) {
         IFileParam fileParam = ((FileUpload) getComponentByName("myFileUpload")).getFile();
         if (fileParam != null) {
              // get info about this file and create a FileInputStream
              File f = fileParam.getFile();
              if (f != null) {
                   try {
                        fis = new FileInputStream(f);
                   // process exceptions opening files
                   catch (FileNotFoundException ex) {
                        myBean.setMessage(
                             "1" + f + ex.getLocalizedMessage());
                   isr = new InputStreamReader(fis);
                   br = new BufferedReader(isr);
    String textLine = "";
    do {
         try {
              textLine = (String) br.readLine();
         } catch (IOException e) {
              myBean.setMessage(
                   "1" + e.getLocalizedMessage());
         // Jco append table & put data into the record
         // (I_FILE is the table with txt data that is sent to the RFC)
         I_FILE.appendRow();     
         I_FILE.setValue(textLine, "REC");                              
    } while (textLine != null);

  • StreamCorruptedException: does not contain a serialized object?

    Can someone tell me why am I getting this exception:
    C:\javapr>java FetchObject
    Couldn't retrieve binary data: java.io.StreamCorruptedException: InputStream
    does not contain a serialized object
    java.io.StreamCorruptedException: InputStream does
    not contain a serialized object
    at java.io.ObjectInputStream.readStreamHeader
    (ObjectInputStream.java:849)
    at java.io.ObjectInputStream.<init>
    (ObjectInputStream.java:168)
    at FetchObject.main(FetchObject.java:23)
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    class FetchObject implements Serializable {
        public static void main (String[] args) {
            try {
                String driver = "oracle.jdbc.driver.OracleDriver";
                Class.forName(driver);
                String url = "jdbc:oracle:thin:@mymachine:1521:homedeva";
                Connection conn = DriverManager.getConnection(url,"cnn","cnn");
                FetchObject i = new FetchObject();
                    // Select related
                    try
                         byte[] recdBlob = i.selectBlob( 1 , conn ); 
                         ByteArrayInputStream bytes = new ByteArrayInputStream(recdBlob);
                         ObjectInputStream deserialize = new ObjectInputStream( bytes );
              Employee x = (Employee)deserialize.readObject();
                    catch( Exception ex )
                  System.err.println("Couldn't retrieve binary data: " + ex);
                  ex.printStackTrace();
         catch( Exception ex )
              ex.printStackTrace();
        public byte[] selectBlob( int id, Connection conn )
         byte[] returndata = null;
         try
              Statement stmt = conn.createStatement();
              String sql = "SELECT id, rowdata FROM blobs WHERE id = " + id;
              ResultSet rs = stmt.executeQuery(sql);
              if ( rs.next() )
                           try
                               ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                               BufferedInputStream bis = new BufferedInputStream( rs.getBinaryStream("rowdata") );
                             byte[] bindata = new byte[4096];
                               int bytesread = 0;
                               if ( !rs.wasNull() )
                                       if ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 )
                                          baos.write(bindata,0,bytesread);
                                returndata = baos.toByteArray();
                             baos.flush();
                                bis.close();
                       catch ( Exception ex )
                            System.err.println("Problem retrieving binary data: " + ex);
                        rs.close();
                         stmt.close();  
               catch ( Exception ex )
                    System.err.println("Couldn't retrieve binary data: " + ex);
            return returndata;
    import java.io.*;
    class Employee implements Serializable
         private String lastName;
         private String firstName;
         public Employee(String lastName, String firstName)
              this.lastName = lastName; 
              this.firstName = firstName;
    }

    To clarify I have stored an Employee Object as a Blob in the Oracle database and am attempting to retreive the
    Employee Object from this Blob.
    Thanks

  • Java.io.StreamCorruptedException: InputStream does not contain a serialized object

              I have an applet which calls a JSP to write data object to the db and then the
              JSP sends back the updated data object. The writing part is ok but the response
              is giving the following error. The data object is in a separate class which implements
              Serialized.
              Here's the code in the applet calling the JSP and the response from the JSP
              URL server = null;
              String urlConnectionString = "http://localhost:7001/isLoginValid.jsp";
              try
              server = new URL(urlConnectionString);
              catch(MalformedURLException e)
              System.out.println("URL exception: " + e );
              // send request
              ObjectInputStream response = null;
              Object result = null;
              try
              URLConnection conn = server.openConnection();
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "application/octet-stream");
              ObjectOutputStream request = new ObjectOutputStream(new
              BufferedOutputStream(conn.getOutputStream()));
              request.writeObject((Object)dvo);
              request.flush();
              request.close();
              // get the result input stream
              response = new ObjectInputStream(new BufferedInputStream
              (conn.getInputStream()));
              // read response back from the server
              result = response.readObject();
              if( result!=null && (result instanceof DataVO))
              dvo = (DataVO)result;
              String vo = dvo.printDataVO();
              System.out.println("*DataVO*\n"+vo);
              else
              System.out.println("not an instanceof DataVO");
              catch(IOException ignored)
              System.out.println("Error in DataVO response");
              ignored.printStackTrace();
              Here's the code in the JSP sending the response back to the applet. The 'dvo'
              object is the object which is serialized and has gets and sets for the diff. data
              elements. When I print the 'dvo' before writing the object to outputStream it
              prints the correct values for the data element.
              // send response
              response.setStatus(HttpServletResponse.SC_OK);
              ObjectOutputStream outputStream = new ObjectOutputStream (new BufferedOutputStream
              (response.getOutputStream()));
              outputStream.writeObject(dvo);
              outputStream.flush();
              ERROR is as follows:
              Error in DataVO response
              java.io.StreamCorruptedException: InputStream does not contain a serialized object
              at java/io/ObjectInputStream.readStreamHeader
              at java/io/ObjectInputStream.<init>
              What am I doing wrong?. Please respond soon. The applet is run on IIS and the
              JSP in on weblogic 6.1. I'm not sure if that makes any difference.
              

              I have an applet which calls a JSP to write data object to the db and then the
              JSP sends back the updated data object. The writing part is ok but the response
              is giving the following error. The data object is in a separate class which implements
              Serialized.
              Here's the code in the applet calling the JSP and the response from the JSP
              URL server = null;
              String urlConnectionString = "http://localhost:7001/isLoginValid.jsp";
              try
              server = new URL(urlConnectionString);
              catch(MalformedURLException e)
              System.out.println("URL exception: " + e );
              // send request
              ObjectInputStream response = null;
              Object result = null;
              try
              URLConnection conn = server.openConnection();
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "application/octet-stream");
              ObjectOutputStream request = new ObjectOutputStream(new
              BufferedOutputStream(conn.getOutputStream()));
              request.writeObject((Object)dvo);
              request.flush();
              request.close();
              // get the result input stream
              response = new ObjectInputStream(new BufferedInputStream
              (conn.getInputStream()));
              // read response back from the server
              result = response.readObject();
              if( result!=null && (result instanceof DataVO))
              dvo = (DataVO)result;
              String vo = dvo.printDataVO();
              System.out.println("*DataVO*\n"+vo);
              else
              System.out.println("not an instanceof DataVO");
              catch(IOException ignored)
              System.out.println("Error in DataVO response");
              ignored.printStackTrace();
              Here's the code in the JSP sending the response back to the applet. The 'dvo'
              object is the object which is serialized and has gets and sets for the diff. data
              elements. When I print the 'dvo' before writing the object to outputStream it
              prints the correct values for the data element.
              // send response
              response.setStatus(HttpServletResponse.SC_OK);
              ObjectOutputStream outputStream = new ObjectOutputStream (new BufferedOutputStream
              (response.getOutputStream()));
              outputStream.writeObject(dvo);
              outputStream.flush();
              ERROR is as follows:
              Error in DataVO response
              java.io.StreamCorruptedException: InputStream does not contain a serialized object
              at java/io/ObjectInputStream.readStreamHeader
              at java/io/ObjectInputStream.<init>
              What am I doing wrong?. Please respond soon. The applet is run on IIS and the
              JSP in on weblogic 6.1. I'm not sure if that makes any difference.
              

  • Creating a converter for old serialized objects

    Hi,
    I have an application, which writes class objects to file, and then reads the class objects from file when the application is started up.
    Now the problem is, that if i create/modify/etc fields in the class, then all my data is lost (i.e., i cant read the data in when the application starts)....
    Now the docs state that a field can be added, and an old serialized object will still be recoverable...well for some reason this only works when it wants....i have tried several times, and its not a guarenteed thing....
    So i was wondering, is there any way to create an application, which can grab an old serialized version of an object (i.e. class), have a copy of the old class, and the new class, and somehow cast the old to the new...or something of that sort?
    thanks a lot!

    This might be of some help:
    http://www.onjava.com/pub/a/onjava/excerpt/JavaRMI_10/?page=5

  • How to divide big serialized object in parts to be able to save as Blob typ

    Hi,
    Actually i have serialize a big XML document object and want to save in a field of type Blob. As Blob size is 64k. So if the serialized object is greater than 64k. It gives me error of size.Can anybody tell how to break large serialized objects.
    I am using this code
    File f = new File("out.ser");
    FileInputStream fin = new FileInputStream(f);
    p = farCon.prepareStatement("insert into TeeColor values('3',?)");
    p.setBinaryStream(1, fin, f.length());
    p.executeUpdate();
    This code works fine if the size of out.ser file is less than 64k. But does not work for bigger sizes
    Please help me out
    Thanks

    Read your data from the file into a byte array, then extract 64K at a time into a smaller byte array, and use a ByteArrayInputStream for updating the database.

  • Problem with serialized objects and JWS

    My JWS launched application fails when loading a serialized object that has been instatiated from a class not contained in the signed jar-file. Does anyone know why this happens and if there is some workaround for the problem?

    Where is the class contained then?

  • Reducing Size of Serialized Object

    Does anyone know how to crunch the size of the serialized object? My serialized objects are exceeding 20 megabytes and it's going to cost a lot of bandwidth transfers within our network.
    Thanks. :-)

    Make any fields transient that you can compute on the other side. If they're still too big after zipping them you may have to use another mechanism other then serialization: extract the minimum necessary data to create the objects and send it over using your own protocol.
    I should note that most modems all ready do hardware compression so compressing it yourself may not improve performance much.

  • A General serialized object

    Hi!
    I'm trying to create some server software that will allow any number of applets to connect to the server and communicate with each other. Presumably, only applets of the same type would talk together, though applets could send general string messages. I've created a general serialized object, Packet, which all applets would send to the server, and which the server would then pass on to the destination applet(s).
    The problem is that Packet has a field "data" of type Object. When data is something the server knows about, such as a String or a Vector, it does ok. But if the code for the applets creates a new class, say AppletPacket (which is serializable), and sets somePacket.data to an object of type AppletPacket, the server throws errors when it is reading the somePacket from its objectinputstream, saying it can't typecast something of type AppletPacket. But I'm not typecasting anywhere! The server doesn't have to know anything about what data represents, it just needs to send it on, and presumably the destination applets will know what to do with it.
    Can anyone suggest a work around, or tell me what I have to do so that applets can send a general Object that may represent a class the server doesn't know about and not have the server throw an error?
    Thanx
    Jim D.

    Just to clairify: The server doesn't have to do anything with the content of "data" apart from holding on to it, and pass it to another applet?
    If that's the case substitute the Object in the "data" field for an array of bytes obtained by having the applet run the "Object" through ObjectOutputStream.
    What's happening is that the server is deserializing the Packet when it arrives in the JVM of the server, when it comes across the "data" field it looks to see what class the instance really is, and fails as you dscribe if it doesn't have the class definition.

  • Size of serialized Objects

    Hello everybody,
    When I serialize a object to a Byte Array the size of the Byte Array is not exactly the size of the object because of some meta data information. Is there any way there I can predict excatly the size that the Object will have when I serialize it? Of course I known the attributes size of this Object.
    For example if I have an Object X with two attributes Integer A and B with 4 bytes each, I'd like to predict that the Byte Array of this serialized Object wil have 10 bytes (8 for the two attributes and 2 for meta data). Does anybody have an idea?
    Thanks,
    Bruno

    Is
    there any way there I can predict excatly the size
    that the Object will have when I serialize it?Yes. You can serialize it to a byte array, then take the size of that. Then you can send the byte array instead of serializing the original object.
    Basically this is something that's very unlikely to be useful. What are you trying to achieve and why do you think you need to know this information?
    Dave.

  • Serializing objects with the NIO API

    I try to use the new IO API to implement a non-blocking multi-threaded server that communicates with client applications by exchanging serialized objects. I started from the code in the JavaWorld article at http://www.javaworld.com/javaworld/jw-09-2001/jw-0907-merlin.html .
    With the new features of J2SDK 1.4.0, you don't have to create a separate thread per connected client. That is a big improvement.
    But when I read an object with ObjectInputStream, I get a java.nio.channels.IllegalBlockingModeException.
    Has anybody successfully implemented such a server since the release of the new io API?
    Thanks.
    Jean-Robert

    The ObjectStream code is basically incompatible with non blockin I/O since you must block on the stream until a whole Object is available. You could roll something like this yourself, by reading bytes until there are enough available to build the next object and then getting that Object from the buffer and shipping it to your client thread. All of this is far more trouble than just using the Stream oriented I/O.
    NIO and mutilple threads are a nightmare, the whole idea of non-blocking I/O is to avoid needing multiple threads. If you do use multiple threads you will need queues between them. See the Taming the NIO Circus topic for lots of discussion of NIO and its problems. The system seems more stable in JDK 1.5, but most people haven't even started using 1.4 for production yet.
    Personally I avoid ObjectStreams. They are only useful between Java applications, if I want that I just use RMI and let Java do ALL the hard work. When I write a Socket based app, its probably because the other end is a mainframe of a C program. For that reason I send data as bytes, packaged up in packets, and encode as XML or ASN.1 so the other end can interpret it.

  • Saving and loading serialized objects (StreamCorruptedException)

    Hello,
    I am relatively new to Serialization (coming to that, a bit new to Java too) and I am having a problem with the following:
    I am saving a number of serialized objects (all of the same class) in a file using the following way (the method is called multiple times to save a list of TeamMember objects):
    Note: TeamMember is a custom class.
    public void addTeamMember(TeamMember p) {
                outputStream = new ObjectOutputStream( new FileOutputStream( "team.dat", true ) );
                outputStream.writeObject( p );
                outputStream.flush();
                outputStream.close();
                outputStream = null;
    }Then I'm trying to retrieve the objects from the file and display them. The method used is the following (it will loop through the file until found or it throws an EOFException. Is using the EOFException good practice to search through the entire file?):
    public TeamMember getTeamMember(String id) {
            TeamMember currentMember = null;
            try {
                boolean found = false;           
                inputStream = new ObjectInputStream( new FileInputStream( "team.dat" ) );
                while ( !found ) {
                    currentMember = (TeamMember)inputStream.readObject();
                    if ( currentMember.getId().equals( id ) )
                        found = true;
                } // end while
                closeInputFile();
                return currentMember;
            } // end try
            catch ( EOFException e ) { // end of file reached
                closeInputFile();           
                return null;
            } // end catch
            catch ( IOException e ) {
                closeInputFile();
                System.err.println( e.getMessage() );
                return null;
            } // end catch
        }Now as a test, I am adding 3 members with IDs 1, 2 and 3 respectively. Then I am calling getTeamMember three times with the different IDs. With ID "1", it works fine. When I give it ID 2, it gives an IOException with message "StreamCorruptedException: invalid type code: AC".
    While tracing the program, I've seen that it always gives me that error when reading past the first object saved in the file.
    Am I saving the objects in a wrong way, or reading them is done incorrectly?
    Any help is much appreciated.
    I hope I was clear enough, and that I posted in the correct forum.
    Thanks in advance.
    Andrew.

    If that is so, might you hint me for a work around?
    I want to append objects in a single file, then be able to find and read an object from the file.
    Thanks again.
    Andrew

  • What is the Error (de-)serializing object

    Hi all
    I have 2 EJB's one Stateful(Bean1) and Statless (Bean2). Bean1 lookup on Bean2 and get the remote object of Bean2 (Bean2Remote) and but it in a class that implements java.io.Serializable but when we return that class that holds the Bean2 remote the server throws
    com.evermind.server.rmi.OrionRemoteException: Error (de-)serializing object: NamingException: Bean2Remote not found
    Where the serializable class has the reomte and home interfaces of Bean2 with it
    Can any one help in that thanks in advance

    Having the same problem as many others here. I keep getting error message "0xFFFE7958". I have tried about 25 times over several days with 2 different computers using both tiger and panther and I still cant get the file to download. The episode that is giving me trouble is "Orientation" in second season of Lost. I have noticed that other peeps have had trouble with the same file. I don't think it's me!! I won't be downloading any itunes content until this gets fixed.

Maybe you are looking for

  • Advice for HTML and CSS code to enlarge an image when clicked ?

    Hi, When clicking on a thumb image I would like users to able to view an enlarged version in the same webpage and then click on close to go back to the thumb image. This is not in a gallery it is a for sale page which contains 3 images. I am new to t

  • Multilingual captioning, how?

    Hi, I am creating a CD-Rom presentation, the requirements of which are Video and multi-language captioning. I thought this would be a good opportunity to gain experience with OSMF and the Captioning Plugin. I am an FDT user rather than Flash Builder

  • Hyperlinks in footnote

    Hello everybody, after using PDFG and implementing it for customers for quite some time, I have just noticed that PDFG doesn't seem to be able to convert hyperlinks in a Word document when those links are placed in a footnote. If I try to do the same

  • Can I fix(set) the distorted object?

    I received a object to my client. It's distorted by 'Free Distort' effect in illustrator. I want distort path and all. = I want distort object irrevocably. Because of my plotter(big printer) cannot cognize distorted object. When i print distorted obj

  • Where  other JButtons  ,where the colour  and where JLabel in the applicat-

    hi guys when I runned this program in an application only last Jbutton which is (9) appeared only the standard colour has appeared for me observe I used these objects pane.setBackground(java.awt.Color.red); setBackground(Color.white);} and JLabel has