StreamCorruptedException using readObject()

I wrote a object to .ser file using writeObject().
and then again opened the file for writing in append mode,
and wrote again a object to the .ser file.
now the problem is using readObject() for the first time retrieve the first object added.
but again doing a readObject() does not return the second object added.instead it throws
java.io.StreamCorruptedException.folowing is the sample code
          File file = new File("/home/dhans/travelcache/test.ser");
          ObjectOutputStream os = new ObjectOutputStream(
               new BufferedOutputStream(new FileOutputStream(file)));
          HashMap hm = new HashMap();
          hm.put("cd", "1001");
          os.writeObject(hm);
          os.flush();
          os.close();          
          ObjectOutputStream os1 = new ObjectOutputStream(
                    new BufferedOutputStream(new FileOutputStream(file, true)));
// OPENED FILE FOR append mode
               HashMap hm1 = new HashMap();
               hm1.put("cd1", "1002");
               os1.writeObject(hm1);
               os1.flush();
               os1.close();          
          ObjectInputStream is = new ObjectInputStream(
                    new BufferedInputStream(new FileInputStream(file)));
          HashMap hm2 = (HashMap)is.readObject();
          HashMap hm3 = (HashMap)is.readObject(); // exception occurs HERE
          is.close();but if i add the two objects at a time like
          ObjectOutputStream os = new ObjectOutputStream(
               new BufferedOutputStream(new FileOutputStream(file)));
          HashMap hm = new HashMap();
          hm.put("cd", "1001");
                os.writeObject(hm);
               HashMap hm1 = new HashMap();
          hm1.put("cd1", "1002");
          os.writeObject(hm1);using the readObject() two times does not throw any exception.
but my requirement is i have to open the file for append mode again to write the second and successive objects .
any help would be helpful.
thanks,
dhanasekaran

Sory, I hadn't checked the src until u said. Coz I ws jst using the APIs.
Nw that I've checked the src....here's the complete code that writes to the file
public void write (File f) {
     try {
          ObjectOutputStream oos =
                     new ObjectOutputStream(new FileOutputStream(f));
          oos.writeObject(this);
          oos.close();
     catch (IOException e) {
          System.err.println("Exception writing file " + f + ": " + e);
private void writeObject (ObjectOutputStream out) throws IOException {
     int i, size;
     out.writeInt (CURRENT_SERIAL_VERSION);
     out.writeObject(inputPipe);
     out.writeObject(outputPipe);
     out.writeObject (inputAlphabet);
     out.writeObject (outputAlphabet);
     size = states.size();
     out.writeInt(size);
     for (i = 0; i<size; i++)
          out.writeObject(states.get(i));
     size = initialStates.size();
     out.writeInt(size);
     for (i = 0; i <size; i++)
          out.writeObject(initialStates.get(i));
     out.writeObject(name2state);
     if(weights != null) {
          size = weights.length;
          out.writeInt(size);
          for (i=0; i<size; i++)
               out.writeObject(weights);
     }     else {
          out.writeInt(NULL_INTEGER);
     if(constraints != null) {
          size = constraints.length;
          out.writeInt(size);
          for (i=0; i<size; i++)
               out.writeObject(constraints[i]);
     }     else {
          out.writeInt(NULL_INTEGER);
     if (expectations != null) {
          size = expectations.length;
          out.writeInt(size);
          for (i=0; i<size; i++)
               out.writeObject(expectations[i]);
     } else {
          out.writeInt(NULL_INTEGER);
     if(defaultWeights != null) {
          size = defaultWeights.length;
          out.writeInt(size);
          for (i=0; i<size; i++)
               out.writeDouble(defaultWeights[i]);
     }     else {
          out.writeInt(NULL_INTEGER);
     if(defaultConstraints != null) {
          size = defaultConstraints.length;
          out.writeInt(size);
          for (i=0; i<size; i++)
               out.writeDouble(defaultConstraints[i]);
     }     else {
          out.writeInt(NULL_INTEGER);
     if (defaultExpectations != null) {
          size = defaultExpectations.length;
          out.writeInt(size);
          for (i=0; i<size; i++)
               out.writeDouble(defaultExpectations[i]);
     }     else {
          out.writeInt(NULL_INTEGER);
     if (weightsPresent != null) {
          size = weightsPresent.length;
          out.writeInt(size);
          for (i=0; i<size; i++)
               out.writeObject(weightsPresent[i]);
     }     else {
          out.writeInt(NULL_INTEGER);
     if (featureSelections != null) {
          size = featureSelections.length;
          out.writeInt(size);
          for (i=0; i<size; i++)
               out.writeObject(featureSelections[i]);
     } else {
          out.writeInt(NULL_INTEGER);
if (weightsFrozen != null) {
size = weightsFrozen.length;
out.writeInt (size);
for (i = 0; i < size; i++)
out.writeBoolean (weightsFrozen[i]);
} else {
out.writeInt (NULL_INTEGER);
     out.writeObject(globalFeatureSelection);
     out.writeObject(weightAlphabet);
     out.writeBoolean(trainable);
     out.writeBoolean(gatheringConstraints);
     out.writeBoolean(gatheringWeightsPresent);
     //out.writeInt(defaultFeatureIndex);
     out.writeBoolean(usingHyperbolicPrior);
     out.writeDouble(gaussianPriorVariance);
     out.writeDouble(hyperbolicPriorSlope);
     out.writeDouble(hyperbolicPriorSharpness);
     out.writeBoolean(cachedValueStale);
     out.writeBoolean(cachedGradientStale);
     out.writeBoolean(someTrainingDone);
     out.writeInt(featureInducers.size());
     for (i = 0; i < featureInducers.size(); i++) {
          out.writeObject(featureInducers.get(i));
     out.writeBoolean(printGradient);
     out.writeBoolean (useSparseWeights);
out.writeInt (transductionType);
//Serialization of MaximizableCRF
private static final long serialVersionUID = 1;
private static final int CURRENT_SERIAL_VERSION = 0;
private void writeObject (ObjectOutputStream out) throws IOException {
          out.writeInt (CURRENT_SERIAL_VERSION);
          out.writeObject(trainingSet);
          out.writeDouble(cachedValue);
          out.writeObject(cachedGradient);
          out.writeObject(infiniteValues);
          out.writeInt(numParameters);
          out.writeObject(crf);

Similar Messages

  • ClassNotFoundException while using readObject.

    I have a servlet that queries a database and creates a object called Notice (an object that implements Serializable), and sends
    it to an applet.
    My problem is that I get a ClassNotFoundException when I try to cast the object back (Notice) when i read the object in the Applet.
    The Notice class is belonging to a package named no.apt.annonse.notice.
    My CLASS_PATH = <my dir>\classes. My packages start in this directory.
    Client routine for reading the object send by the servlet:
    try{
    ObjectInputStream input;
    URL noticeServlet = new URL(getCodeBase(),<my dir>);
    URLConnection servletConnection = noticeServlet.openConnection();
    servletConnection.setUseCaches (false);
    servletConnection.setDefaultUseCaches(false);
    input = new ObjectInputStream(servletConnection.getInputStream());
    notice = (Notice)input.readObject();
    catch(MalformedURLException mfURLe){
    <my message>
    catch(IOException ioe){
    <my message>
    catch(ClassNotFoundException cnfe){
    <my message>
    Servlet routine for sending the object form the servlet:
    ObjectOutputStream outputToApplet;
    try{
    outputToApplet = new ObjectOutputStream(response.getOutputStream());
    outputToApplet.writeObject(notice);
    outputToApplet.close();          
    catch (IOException e){
    <my message>
    catch(Exception ex){
    <my message>
    Please excuse my bad english

    The problem is that the readObject() method of ObjectInputStream needs the class file of Notice to be able to create your Object in the Applet.
    You need to make Notice.class available to the Applet through the Applet's class path.

  • Reg. StreamCorruptedException

    Hi,
    Can U help me How 2 solve "StreamCorruptedException" problem.
    This exception i'm getting when i'm trying 2 use readObject().
    First time it is giving EOFException().from next time onwards it is giving StreamCorruptedException().
    code is:
    import java.io.*;
    public class FileTry1
    // instance variables - replace the example below with your own
    private UserRec currUser;
    * Constructor for objects of class FileTry1
    public FileTry1()
    // initialise instance variables
    UserRec u1 = new UserRec(0, "John3", 1000);
    UserRec u2 = new UserRec(1, "joe3", 2000);
    UserRec u3 = new UserRec(100, "naren", 2000);
    try {
    FileOutputStream ostream = new FileOutputStream("t.tmp", true);
    ObjectOutputStream p = new ObjectOutputStream(ostream);
    p.writeObject(u1);
    p.writeObject(u2);
    p.writeObject(u3);
    p.flush();
    ostream.close();
    p.close();
    catch (Exception e) {
    System.out.println(e);
    } // end catch
    ReadIt ri = new ReadIt();
    public static void main(String args[] ) {
    new FileTry1();
    System.exit(0);
    } // end class FileTry1
    import java.io.*;
    public class UserRec implements Serializable
    // instance variables - replace the example below with your own
    public int userID;
    public String userName;
    public int salary;
    * Constructor for objects of class UserRec
    public UserRec()
    // initialise instance variables
    userID = 0;
    userName = "";
    salary = 0;
    public UserRec(int id, String name, int sal) { 
    // overridden constructor w/ values
    userID = id;
    userName = name;
    salary = sal;
    } // end constructor...
    import java.io.*;
    public class ReadIt
    // instance variables - replace the example below with your own
    private UserRec urec;
    * Constructor for objects of class ReadIt
    public ReadIt()
    // initialise instance variables
    urec = new UserRec();
    FileInputStream istream = null;
    ObjectInputStream p = null;
    // now try to read the file we just wrote
    try {
    istream = new FileInputStream("t.tmp");
    p = new ObjectInputStream(istream);
    System.out.println("Now going to try to read the file back in");
    boolean EOF = false;
    int count=0;
    while ( !EOF ) {
    try {
    UserRec t_urec = (UserRec) p.readObject();
    System.out.println("rec No.: " + t_urec.userID + " Name: " + t_urec.userName);
    if(++count == 4) break;
    } // end try
    catch (Exception f) {
    EOF = true;
    System.out.println("in ReadIt at EOF catch: " + f);
    f.printStackTrace();
    } // end catch EOF
    } // end while ( !EOF )
    istream.close();
    p.close();
    } // end try
    catch (Exception ee) {
    System.out.println("Overall ReadIt catch: " +ee);
    } // end ReadIt()
    } // end class ReadIt
    Thanks in advance
    Naren.

    in ReadIt class you make 4 as 3 For your convinenece i am pasting all the files back compiled and runned,
    import java.io.*;
    public class FileTry1
    // instance variables - replace the example below with your own
    private UserRec currUser;
    * Constructor for objects of class FileTry1
    public FileTry1()
    // initialise instance variables
    UserRec u1 = new UserRec(0, "John3", 1000);
    UserRec u2 = new UserRec(1, "joe3", 2000);
    UserRec u3 = new UserRec(100, "naren", 2000);
    try {
    FileOutputStream ostream = new FileOutputStream("t.tmp", true);
    ObjectOutputStream p = new ObjectOutputStream(ostream);
    p.writeObject(u1);
    p.writeObject(u2);
    p.writeObject(u3);
    p.flush();
    p.close();
    ostream.close();
    catch (Exception e) {
    System.out.println(e);
    } // end catch
    ReadIt ri = new ReadIt();
    public static void main(String args[] ) {
    new FileTry1();
    System.exit(0);
    } // end class FileTry1
    import java.io.*;
    public class ReadIt
    // instance variables - replace the example below with your own
    private UserRec urec;
    * Constructor for objects of class ReadIt
    public ReadIt()
    // initialise instance variables
    urec = new UserRec();
    FileInputStream istream = null;
    ObjectInputStream p = null;
    // now try to read the file we just wrote
    try {
    istream = new FileInputStream("t.tmp");
    p = new ObjectInputStream(istream);
    System.out.println("Now going to try to read the file back in");
    boolean EOF = false;
    int count=0;
    while ( !EOF ) {
    try {
    UserRec t_urec = (UserRec) p.readObject();
    System.out.println("rec No.: " + t_urec.userID + " Name: " + t_urec.userName);
    if(++count == 3) break;
    } // end try
    catch (Exception f) {
    EOF = true;
    System.out.println("in ReadIt at EOF catch: " + f);
    f.printStackTrace();
    } // end catch EOF
    } // end while ( !EOF )
    istream.close();
    p.close();
    } // end try
    catch (Exception ee) {
    System.out.println("Overall ReadIt catch: " +ee);
    } // end ReadIt()
    } // end class ReadIt
    import java.io.*;
    public class UserRec implements Serializable
    // instance variables - replace the example below with your own
    public int userID;
    public String userName;
    public int salary;
    * Constructor for objects of class UserRec
    public UserRec()
    // initialise instance variables
    userID = 0;
    userName = "";
    salary = 0;
    public UserRec(int id, String name, int sal) {
    // overridden constructor w/ values
    userID = id;
    userName = name;
    salary = sal;
    } // end constructor...
    }All The Best

  • Help me in readObject

    Hi everyone,
    I am facing a problem while reading from file using readObject. .
    I have a function add() which writes objects to a file. If i display objects after a single call to add the objects gets displayed properly. But if i call add() again and display() only the previous values gets displayed.
    But everything gets added to the file properly. I'm using sequential files
    Pls reply me immediately.
    Thanks in advance,
    Vinoth

    Hi
    this is the code
    import java.io.*;
    import java.util.*;
    public class SerializeFiles implements Serializable
         static BufferedReader console;
         ObjectOutputStream output;
         ObjectInputStream input;
         FileInputStream inputfile;
         FileOutputStream outputfile;
         public SerializeFiles()
         public void openFile()
              try // open file
                   //output = new ObjectOutputStream( new FileOutputStream( "record11.ser" ,true) );
                   //outputfile = new FileOutputStream("record13.ser",true);
                   output = new ObjectOutputStream(outputfile);
              catch ( IOException ioException )
                   System.err.println( "Error opening file." );
              } // end catch
         } // end method openFile
         public void openFile1()
         try // open file
                   //input = new ObjectInputStream(new FileInputStream( "record11.ser" ));
                   //inputfile = new FileInputStream( "record13.ser" );
                   input = new ObjectInputStream(inputfile);
              }     // end try
              catch ( IOException ioException )
                   System.err.println( "Error opening file." );
                   } // end catch
         public void addRecords()throws IOException
              try
              Records record;
              String name,address,email;
              int phone;
              outputfile = new FileOutputStream("record12.ser",true);
              if(output==null)
                   openFile();
              console = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("Enter the number of records to be inserted :");
              int n=Integer.parseInt(console.readLine());
              String read=null,str=null;
              while(n>0)
                   System.out.println("Enter the name :");
                   name=console.readLine();
                   System.out.println("Enter the address :");
                   address=console.readLine();
                   System.out.println("Enter the phone number :");
                   phone=Integer.parseInt(console.readLine());
                   System.out.println("Enter the mail id :");
                   email=console.readLine();
                   record=new Records(name,address,phone,email);
                   output.writeObject(record);
                   n--;
              output.flush();
              catch(Exception e)
              finally
                   //output.close();
                   //outputfile.close();
         public void viewRecords()throws IOException,ClassNotFoundException
              try
              Records record;
              System.out.println("Inside view");
              inputfile = new FileInputStream( "record12.ser" );
              //if(input==null)
                   //System.out.println("inside input....");
              openFile1();
              while(true)
              {     System.out.println("Inside view hh ");
                   record = (Records) input.readObject();
                   System.out.println("Inside view nnh");
                   System.out.println("Records :: "+record.getName()+" "+record.getAddress()+" "
                             record.getPhone()" "+record.getEmail());
              catch(Exception e)
                   System.out.println(e);
              finally
                   input.close();
                   inputfile.close();
         public static void main(String args[])throws IOException,ClassNotFoundException
              SerializeFiles sf=new SerializeFiles();
              console = new BufferedReader(new InputStreamReader(System.in));
              //sf.openFile();
              String choice;
              do
              System.out.println("CHOICE: 1.ADD 2.DISPLAY 3.DELETE 4.MODIFY 5.EXIT");
              System.out.println("Enter your choice of operation :");
              int n= Integer.parseInt(console.readLine());
              switch(n)
              case 1:
                   sf.addRecords();
                        break;
              case 2:
                   // sf.openFile1();
                   sf.viewRecords();
                        break;
              /*case 3:
                   fw.delete();
                        fw.refresh();
                        break;
              case 4:
                   fw.modify();
                        fw.refresh();
                        break;*/
              case 5:
                   System.exit(0);
              System.out.println("Do you want to continue(y/n):");
              choice=console.readLine();
              }while(choice.equals("y"));
    Plz help me

  • Do I need separate thread for readObject() and writeObject()?

    Somehow, my Client/Server code behaves badly. A click on
    the GUI did not always send a message to the Server as
    intented (using writeObject(String)). Most of the times the
    message was sent. But not always.The Client (GUI) also uses
    readObject() to receive messages from the Server. Is this
    problem associated with the fact that my readObject() and
    writeObject() from the GUI are on the same thread? Need
    some help.
    Thank you.

    "and I don't do GUIs"
    First, let me say, as a Newbie, how good it feels to
    even be able to follow this.
    But I honestly don't understand the above quoted
    comment from jverd.
    How does somebody do Java and not do GUI stuff?
    It almost sounds like a plumber saying "I don't do
    sinks."
    Even from my novice perspective, Java seems slow and
    sucks copious amounts of memory.
    Is there any practical use for Java if you're not
    doing GUIs?In my experience, it's often the GUIs that make it slow. Apparently things are better if you use Swing carefully, or use SWT or maybe AWT.
    As far as I can tell, the vast majority of Java code that's out there is backend stuff. Not that I've done a formal survey. I can tell you from personal experience however, that there is a LOT of stuff that Java is good for besides GUIs (business logic behind websites being one of its major areas of use), and if you write reasonably good code, it will be very fast.
    Your analogy might be better couched as "an auto mechanic saying 'I don't do body work.'"

  • NativeProcess and IDataInput readObject()

    I have seen references on various site regarding this issue but am still getting this issue pretty consistently so thought I would see if I could get some support from here.
    Basically on reading a standard output from a NativeProcess I attempt to read the IDataInput using readObject and get #2030 End of file was encountered.  I can read as a String via readUTFBytes no problem.  So whats the process to manage this IDataInput as something other than a String i.e. Object, XML etc?
    Bearing in mind that I have no control over the data type received from the NativeProcess?
    Cheers,
    Simon

    Yes, it is separately. For another experimenting, I'm running multi-chatroom
    on xSocket in Java, I tried to get NP launch the chat (client) also created
    in Java, not passing any message/info back to NP but to xSocket server. I
    was surprise the client would stop sending/working suddenly, no error
    message on both sides. If I don't use NP, it work flawlessly and able to
    handle large volume of data without lost or significant delay. I am
    disappoint that NP is incapable for production use.
    I tried adding "flush" before and after the text is display in Java code but
    it doesn't solve. Someone may solve it but how many programs are available
    in sourcecode?

  • DataSetData class not found while Using Streamable Data Set

    Hi
    I am trying to populate a gridcontrol with the help of a DB
    servlet.The servlet has a querydataset on the server side.
    According to the online document i.e using " Streamable
    DataSets" I am trying to use the class DataSetData and the
    method DataSetData.extractDataSet.
    The document says:
    "The server may use JDeveloper QueryDataSets to provide the data
    to the server machine. The data can be extracted using
    DataSetData.extractDataSet and sent over a
    wire to the client.The DataSetData object implements the
    java.io.Serializable interface and may subsequently be
    serialized using writeObject in java.io.ObjectOutputStream and
    read using readObject in java.io.ObjectInputStream. This method
    turns the data into a byte array and passes it through sockets
    or some other transport medium. Alternatively, the object
    can be passed via Java RMI, which will do the serialization
    directly."
    I searched for this class the entire JBCL package and also other
    packages.I could not locate the class and the constructors and
    methods that I can use.The explanation in the online document
    about this is also trivial.I have no idea on how do I use this.
    I need some information on how to use this class.
    I also need some info on the data access and exchange between
    JBCL controls on the applet and servlet like how do I stream a
    querydataset such that I can populate my grid control.
    Thanks
    Ram
    null

    Hi
    Thanks , But when will I be able to use this.How long will this
    take.
    Is there any workaround for this.?
    Thanks
    Ram
    JDeveloper Product Management (guest) wrote:
    : Ram (guest) wrote:
    : : Hi
    : : I saw a similar question posted in JBuilder news group,.
    : : The J builder QA team is of the opinion that the DataSetData
    : : classes and other high end database stuff are bundled in the
    : : JBuilder Client / Server edition.
    : : Is there anything like that in Jdeveloper 2.0 or do I have
    to
    : : wait till the production release.
    : : If there is a way to do this with the beta , I would also
    like
    : : to see a small example of this or a way to do this.
    : : Thanks in advance
    : : Ram
    : We will be shipping `Java Business Objects' and InfoBus
    : Federico
    null

  • Need help with ObjectInputStream

    i'm sending a serialized object over an ObjectInputStream, this object has a display function. my server uses readObject in a while true loop and everytime he gets an object he prints object.display. everytime i send an object the server recieves it but the display function shows the same thing as it showed in the first sent object, what can cause it?
    here is my code:
    while(true)
    SmilyParser s=(SmilyParser)in.readObject();
    System.out.println("something recieved");
    s.display();
    }

    public void Send(SmilyParser SP) throws Exception
            //out.flush();
            //out.reset();
            if(out==null)
                out = new ObjectOutputStream(clientSocket.getOutputStream());
            System.out.println("ready to send SmilyParser");//testing
            out.writeObject(SP);
            System.out.println("SmilyParser sent");//testing
           // out.flush();
            out.reset();
        }

  • Help with displaying my xml file in my jtext area

    Hi i am trying to read the data from my xml file and display it once the user clicks on the list all button.
    below is the source code for my program can someone please tell me some code to this.
    package tractorgui;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.XMLEncoder;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.beans.XMLDecoder;
    import javax.swing.*;
    import javax.swing.border.LineBorder;
    //import tractor.TextInputPrompt;
    import tractor.Tractor;
    * This code was edited or generated using CloudGarden's Jigloo
    * SWT/Swing GUI Builder, which is free for non-commercial
    * use. If Jigloo isbeing used commercially (ie, by a corporation,
    * company or business for any purpose whatever) then you
    * should purchase a license for each developer using Jigloo.
    * Please visit www.cloudgarden.com for details.
    * Use of Jigloo implies acceptance of these licensing terms.
    * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
    * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
    * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
    public class NewSwingApp extends javax.swing.JFrame {
    //          //Set Look & Feel
    //          try {
    //               javax.swing.UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
    //          } catch(Exception e) {
    //               e.printStackTrace();
              private static final long serialVersionUID = 1L;
         private JButton searchmanufacturer;
         private JButton jButton3;
         private JLabel companyname;
         private JPanel labelpannel;
         private JButton listall;
         private JPanel MenuButtons;
         private JButton archivetractor;
         private JTextArea outputscreen;
         private JButton exhibittractor;
         private JButton deletetractor;
         private JButton addtractor;
         private JButton listallexbited;
         private Tractor [ ] tractors;
         private JScrollPane jScrollPane2;
         private JScrollPane jScrollPane1;
    private int numberOfTractors;
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        NewSwingApp inst = new NewSwingApp();
                        inst.setLocationRelativeTo(null);
                        inst.setVisible(true);
         public NewSwingApp() {
              super();
              initGUI();
         private void initGUI() {
              try {
                   BorderLayout thisLayout = new BorderLayout();
                   getContentPane().setLayout(thisLayout);
                   this.setPreferredSize(new java.awt.Dimension(750, 700));
                        labelpannel = new JPanel();
                        BorderLayout labelpannelLayout = new BorderLayout();
                        getContentPane().add(labelpannel, BorderLayout.NORTH);
                        labelpannel.setLayout(labelpannelLayout);
                        jButton3 = new JButton();
                        getContentPane().add(getExitsystem(), BorderLayout.SOUTH);
                        jButton3.setText("Exit System");
                        jButton3.setPreferredSize(new java.awt.Dimension(609, 57));
                        jButton3.setBackground(new java.awt.Color(0,255,255));
                        jButton3.setForeground(new java.awt.Color(0,0,0));
                        jButton3.setFont(new java.awt.Font("Arial",1,24));
                        jButton3.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent evt) {
                                            System.exit(0);
                        MenuButtons = new JPanel();
                        getContentPane().add(MenuButtons, BorderLayout.WEST);
                        GridLayout MenuButtonsLayout = new GridLayout(7, 1);
                        MenuButtonsLayout.setColumns(1);
                        MenuButtonsLayout.setRows(7);
                        MenuButtonsLayout.setHgap(5);
                        MenuButtonsLayout.setVgap(5);
                        MenuButtons.setLayout(MenuButtonsLayout);
                        MenuButtons.setPreferredSize(new java.awt.Dimension(223, 267));
                             listall = new JButton();
                             MenuButtons.add(getListall());
                             listall.setText("List All");
                             listall.setBackground(new java.awt.Color(0,255,255));
                             listall.setForeground(new java.awt.Color(0,0,0));
                             listall.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));
                             listall.setFont(new java.awt.Font("Arial",2,14));
                             listall.addActionListener(new ActionListener() {
                                  /* (non-Javadoc)
                                  * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
                                  public void actionPerformed(ActionEvent evt) {
                                       String XMLFile = "tractor.xml-courseworkasignment/src";
                                       //** Prints the contents of my XML file
                                       try {
                                       String s;
                                       BufferedReader in = new BufferedReader( new FileReader(XMLFile)
                                       outputscreen.setText("File successfully opened");
                                       try {
                                       while ( (s=in.readLine()) !=null)
                                       outputscreen.append(s);
                                       catch(Exception e) {
                                            outputscreen.append("Error reading line: " + e.getMessage());
                                       outputscreen.append("End of Document");
                                       catch(FileNotFoundException e) {
                                            outputscreen.append("Error in opening file: " + e.getMessage());
                             listallexbited = new JButton();
                             MenuButtons.add(getListallexbited());
                             listallexbited.setText("List All Tractors On Exhibition ");
                             listallexbited.setPreferredSize(new java.awt.Dimension(157, 57));
                             listallexbited.setBackground(new java.awt.Color(0,255,255));
                             listallexbited.setForeground(new java.awt.Color(64,0,0));
                             listallexbited.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       outputscreen.repaint();
                                       String XMLFile = "C:tractor.xml";
                                  // Print contents of XML file
                                  try {
                                  String s;
                                  BufferedReader in = new BufferedReader( new FileReader(XMLFile)
                                  outputscreen.setText("File successfully opened");
                                  try {
                                  while ( (s=in.readLine()) !=null)
                                  outputscreen.append(s);
                                  catch(Exception e) {
                                       outputscreen.append("Error reading line: " + e.getMessage());
                                  outputscreen.append("End of Document");
                                  catch(FileNotFoundException e) {
                                       outputscreen.append("Error in opening file: " + e.getMessage());
                             addtractor = new JButton();
                             MenuButtons.add(getAddtractor());
                             addtractor.setText("Add Tractor ");
                             addtractor.setBackground(new java.awt.Color(0,255,255));
                             addtractor.setForeground(new java.awt.Color(64,0,0));
                             addtractor.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       String manufacturer =JOptionPane.showInputDialog(getComponent(0), "Enter Manufacturer of Tractor");
                                       String shp = (JOptionPane.showInputDialog(getComponent(0), "Enter Horse Power of Tractor"));
                                       int hp =Integer.parseInt(shp);
                                       int sisRare =Integer.parseInt(JOptionPane.showInputDialog(getComponent(0), "Enter If the Tractor is rare (1=Yes/2=No)"));
                                       boolean isRare;
                                       if (sisRare== 1) {
                                       isRare =true;     
                                       }else
                                            isRare =false;
                                       String yom= JOptionPane.showInputDialog(getComponent(0), "Enter Year of Manufacture");
                                       int yearOfManufacture =Integer.parseInt(yom);
                                       String yis =JOptionPane.showInputDialog(getComponent(0), "Enter Number of years the Tractor has been in service");
                                       int yearsInService =Integer.parseInt(yis);
                                       String svalue = JOptionPane.showInputDialog(getComponent(0), "Enter Tractor's Value (?Pounds)");
                                       double value = Double.parseDouble(svalue);
                                       String lastWorkPlace =JOptionPane.showInputDialog(getComponent(0), "Enter Last Workplace");
                                            if(NewSwingApp.addTractor(new Tractor(manufacturer, hp, isRare, yearOfManufacture, yearsInService, value, lastWorkPlace, false)))
                                       JOptionPane.showMessageDialog((getComponent(0)), "Tractor Added");
                                       else
                                            JOptionPane.showMessageDialog(getComponent(0), "Could not Add Tractor");
                             deletetractor = new JButton();
                             MenuButtons.add(getDeletetractor());
                             deletetractor.setText("Delete Tractor ");
                             deletetractor.setBackground(new java.awt.Color(0,255,255));
                             deletetractor.setForeground(new java.awt.Color(64,0,0));
                             deletetractor.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       System.out.println("deletetractor.actionPerformed, event="+evt);
                                       JOptionPane.showInputDialog(getComponent(0), "Enter Tractor ID");
                             exhibittractor = new JButton();
                             MenuButtons.add(getExhibittractor());
                             exhibittractor.setText("Exhibit Tractor");
                             exhibittractor.setBackground(new java.awt.Color(0,255,255));
                             exhibittractor.setForeground(new java.awt.Color(0,0,0));
                             exhibittractor.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       System.out.println("exhibittractor.actionPerformed, event="+evt);
                                       JOptionPane.showInputDialog(getComponent(0), "Enter Tractor I.D");
                             archivetractor = new JButton();
                             MenuButtons.add(getArchivetractor());
                             archivetractor.setText("Archive Tractor");
                             archivetractor.setBackground(new java.awt.Color(0,255,255));
                             archivetractor.setForeground(new java.awt.Color(0,0,0));
                             archivetractor.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       System.out.println("archivetractor.actionPerformed, event="+evt);
                                       JOptionPane.showInputDialog(getComponent(0), "Enter Tractor I.D");
                             searchmanufacturer = new JButton();
                             MenuButtons.add(searchmanufacturer);
                             searchmanufacturer.setText("Search Manufacturer");
                             searchmanufacturer.setPreferredSize(new java.awt.Dimension(159, 21));
                             searchmanufacturer.setBackground(new java.awt.Color(0,255,255));
                             searchmanufacturer.setForeground(new java.awt.Color(64,0,0));
                             searchmanufacturer.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent evt) {
                                       System.out.println("searchmanufacturer.actionPerformed, event="+evt);
                                       JOptionPane.showInputDialog(getComponent(0), "Enter Manufacturer Name");
                        outputscreen = new JTextArea();
                        getContentPane().add(outputscreen, BorderLayout.CENTER);
                        outputscreen
                                  .setText("");
                        outputscreen.setBorder(BorderFactory.createTitledBorder(""));
                        outputscreen.setWrapStyleWord(true);
                        outputscreen.setEditable(false);
                        outputscreen.setEnabled(true);
                        outputscreen.setBackground(new java.awt.Color(255, 255, 255));
                        outputscreen.setForeground(new java.awt.Color(64, 0, 0));
                        companyname = new JLabel();
                        getContentPane().add(companyname, BorderLayout.NORTH);
                        companyname.setText(" Wolvesville Tractor Museum");
                        companyname.setPreferredSize(new java.awt.Dimension(609, 85));
                        companyname.setBackground(new java.awt.Color(255,255,0));
                        companyname.setFont(new java.awt.Font("Arial",1,28));
                        companyname.setForeground(new java.awt.Color(0,0,0));
                        companyname.setBorder(BorderFactory.createTitledBorder(""));
                        companyname.setOpaque(true);
                   this.setSize(750, 750);
              } catch (Exception e) {
                   e.printStackTrace();
         protected static boolean addTractor(Tractor tractor) {
                   if (tractor.getManufacturer()==null) return false; else
                   if (tractor.getHp()<50||tractor.getHp()>1100) return false; else
                   if (tractor.getIsRare()==false) return false; else
                   if (tractor.getYearsInService()<1||tractor.getYearsInService()>200) return false; else
                   if (tractor.getYearOfManufacture()<1800||tractor.getYearOfManufacture()>2008) return false; else
                   if (tractor.getValue()<100||tractor.getValue()>1500) return false; else
                   if (tractor.getLastWorkPlace()==null) return false; else
              return true;
         public JPanel getMenuButtons() {
              return MenuButtons;
         public JButton getListall() {
              return listall;
         public JLabel getCompanyname() {
              return companyname;
         public JButton getExitsystem() {
              return jButton3;
         public JButton getSearchmanufacturer() {
              return searchmanufacturer;
         public JButton getListallexbited() {
              return listallexbited;
         public JButton getAddtractor() {
              return addtractor;
         public JButton getDeletetractor() {
              return deletetractor;
         public JButton getExhibittractor() {
              return exhibittractor;
         public JButton getArchivetractor() {
              return archivetractor;
         public JTextArea getOutputscreenx() {
              return outputscreen;
    public void savetractors () {
         try {
              XMLEncoder encoder = new XMLEncoder(new FileOutputStream("tractor.xml"));
              encoder.writeObject(tractors);
              encoder.close();
         } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
    public void loadtractors () {
    try {
              XMLDecoder decoder = new XMLDecoder(new FileInputStream("tractor.xml"));
              tractors = (Tractor[]) decoder.readObject();
              decoder.close();
              for (int i=0; i<tractors.length;i++) {
                   if (tractors!=null)numberOfTractors =i;
              numberOfTractors++;
         } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              tractors=new Tractor[25];
              numberOfTractors=0;

    here's an example:
    http://jdj.sys-con.com/read/37550.htm
    you need to have a class Tractor with all those properties and then use readObject.Somehow you need to tell the Encoder/Decoder what Tractor means..
    hope this helps!!

  • Issue invoking webcatalog webservice in oracle11g

    I am trying to use readObjects method as below
    catalogObject = webCatalogService.readObjects(objectPath, false, eLevel, returnOption, sessionId);
    to read a catalog object from the presentation layer catalog.
    I get SOAPFaultException exception
    The detailMessage in the Exception object is
    Assertion failure: false at line 816 of C:\ADE\aime_bi\bifndn\analytics_web\main/project/websoap/soaphelpers.cpp
    Any idea what this means and what should I look for more debugging?
    Any help very appreciated as this is kind of urgent.
    Thanks,
    Neel

    The code write like this:
    ItemInfo[] items=catalog.getSubItems("/users/weblogic/test","*",true,null,sessionID);
    but I met another question,Reports page's style and pictures are lost.
    Do you know why?

  • No cache hit on one-to-one mapping

    I am experimenting with toplink and have found that toplink does not use cache when I read a object having one-to-one mapping with other object that have been already in memory.
    e.g. I have an employee class that have a field with one-to-one mapping (with no indirection) to a department class
    I have two objects of the employee class, that share the same object of department class (they work in the same department)
    When I read (using readObject ) first object of the employee class, I expect an referenced object of the department class is read and placed in the session cache.
    However when I read second object of the employee class, I recognized that toplink again issue SQL command to read the department class's object

    Hello,
    Is employee-> department mapping using the full department pk in the reference? TopLink by default uses the check cache by primary key on all queries. This means that when the Employee object is built, it will query for the department object. This will cause it to search the cache for the department object only if it can create the full pk from the foreign key fields in the employee table, otherwise it will go to the database. Even though it may go to the database, it will still return the object from the cache to maintain object identity - it will only build the department object if one does not already exist with that pk in the cache.
    Another circumstance this behaviour could occur is if the department object is removed from the identity map through garbage collection, or if no identitymap is being used.
    Please check http://download-west.oracle.com/docs/cd/B10464_01/web.904/b10313/queries.htm#1134704
    for info on TopLink queries with respect to the cache. If this is what is happening in your case and you want to have this specific department query go to the cache first, you can change it using an ammendment method on the employee descriptor. in the ammendment method, you will need to get the department mapping and use the getSelectionQuery() api to modify the associated query.
    Best Regards,
    Chris Delahunt

  • Help in Socket Programing Plz

    Hi everyBody!!!
    I m writing a client/server program in which client requests to the server to get the contents of the directory of the server computer (path of the directory is specified by client).
    Server gets the contents fo the director by using the listFile() method and writes that contents onto the socket.
    but the problem is:
    how i can the read that contents from client side? server writes an array of type File onto the socket by using writeObject() method. And client definately will use readObject() method. but how i can read an array of type File from the client side???

    You gave the answer yourself: The Server may write the ARRAY of Files using write Objects and the Client will use readObject. Arrays are Objects too, so do not loop but just write:
    On server Side
    File [] allFiles = getThemFromSomewhere();
    ObjectOutputStream oout = ...;
    oout.writeObject(allFiles); // no loop here!
    ...On client side:
    ObjectInputStream oin = ...;
    File [] allFiles = (File[])oin.readObject()
    ...Well I don't really understand the way you want to do this, because the Files descriptions will be System dependent (and for FileTransfer FTP was created), so this will only make sense when you do interprocess communication on the same system. What do you want to achieve?

  • ObjectInputStream Question

    For reasons too long to go into I have written a client server with SSL sockets that passes both objects of my own creation and vector containing Strings. My problem is detecting on the server end if the object stream contains my Object or the vectors before I write them to the database.
    So i would like to be able to either be able to tell the type of object in the stream or get a look at what is in the object and then use an if/else to act depending on which object is in the stream. If I use readObject() it means that the data is already deserialized and so by the time I know what my object is it is too late to make a decision about how to process the data.
    Does anyone know a creative use of one of the methods that would give me this info without deserializing the data? Or any suggestions would be very much appreciated
    thanks

    You can use a BufferedInputStream's mark() feature. Something like this should work:
    InputStream is=soc.getInputStream();
    BufferedInputStream bis=new BufferedInputStream();
    bis.mark(10*1024); // at most 10 Kb before mark gets invalidated
    ObjectInputStream ois=new ObjectInputStream(bis);
    Object o=ois.readObject();
    if(o instanceof Vector)
       bis.reset(); // now a second call to ois.readObject() will return the same object
    else
       handle(o);

  • 100 MB characters in object

    We are using java 1.5 in our application on HP UX 11.
    In one of the functionality we are saving java objects to hard disk and reading them later.
    code is like --
    file=new File(path);
    fileOut = new FileOutputStream (file);
    objOut = new ObjectOutputStream (fileOut);
    objOut.writeObject(object);
    objOut.close();
    fileOut.close();
    for reading we use readObject method.
    In normal cases size of object files on disk is not more than 35 kb.
    This works fine in normal scenarios but if end user enters some special characters from MS word or excel then size of files is increased to 100 MB dramatically.If we open the object file in some editor then we can see a series of latin characters like à à à à à à (millions of characters).
    While taking input from application user we are accepting only 20 characters.
    I am not able to understand how single character is converted to millions of characters?
    This is killing JVM...

    Thanks for reply.
    I have created a sample class saveObject for example.This will write object in C drive in case of windows (<1kb).
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.ObjectOutputStream;
    public class saveObject {
        public saveObject() {
        public static void writeObject(Object object , String path) {
               File file=null;
               FileOutputStream fileOut=null;
               ObjectOutputStream objOut=null;
               try {
                   file=new File(path);
                   fileOut = new FileOutputStream (file);
                   objOut = new ObjectOutputStream (fileOut);
                   objOut.writeObject(object);
                   objOut.close();
                   fileOut.close();
               } catch (Exception e){
                    e.printStackTrace();
               } finally {
                   file=null;
                   fileOut=null;
                   objOut=null;
        public static void main(String[] args) {
            writeObject("WallStreet 2nd A LA","C://test.obj");
    }We are facing issue only in HP UNIX . The code works fine in Windows and Linux environment.
    More Details : We have web application in which we accept data from users in html forms and save this to disk on temporary basis.
    Issue is faced with address field where user is doing copy paste from excel/word rather than typing in form.

  • Image FIle Transfer

    This topic may not be appropriate for the 2D forum, but I couldn't find one that deals with images. Please let me know if there's a more appropriate forum.
    I use Java 1.4/JBoss 3.22/Oracle 9i.
    I have a swing client that occasionally needs to transfer image files (jpg and dxf) to and from the database across the WAN. The file size is typically 1MB. I use RMI-over-HTTP for EJB communication between the client and server.
    I need to figure out a way to transfer the files. The ideal would be to bundle BufferedImages in a transfer object that the session bean hands to the client. But, since BufferedImage is not Serializable I need a different method.
    How do people typically do this type of transfer?
    I appreciate any ideas you can offer.
    Thanks,
    --BobC                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I'm the original poster.
    I've solved the problem of transferring BufferedImages between a client and server using an EJB. I wrote a TransferImage class that wraps the BufferedImage in a byte array, which is serializable. Then I transfer an instance of that object using the bean, and then use readObject() to reconstitute the BufferedImage.
    Here is the TransferImage class:
    package com.whatever;
    import java.awt.image.PixelGrabber;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.io.Serializable;
    import java.io.IOException;
    * This class allows BufferedImages to be serialized so that they can be tranferred
    * using an EJB.
    * <p>
    * NOTE: System.out.printlns are used for logging rather than Log4j for serialization.
    * Author: Bob Carpenter [email protected]
    * Date: Feb 4, 2004
    public class TransferImage extends Canvas
    implements Serializable {
    private transient BufferedImage image = null;
    private int imageType = BufferedImage.TYPE_INT_BGR;
    private Object pix = null;
    private int width = 0;
    private int height = 0;
    * Basic ctor.
    * <p>
    * NOTE: Creates serializable pix object from image.
    * @param image buffered image to be transferred
    * @param imageType type of image - see BufferedImage class
    public TransferImage(BufferedImage image, int imageType)
    throws IOException {
    System.out.println("TransferImage.ctor_entry");
    this.image = image;
    this.imageType = imageType;
    writeObject();
    System.out.println("TransferImage.exit_entry");
    * Writes the image to pix object.
    * <p>
    * NOTE: Uses PixelGrabber to create pix object.
    * @throws IOException
    private void writeObject() throws IOException {
    System.out.println("TransferImage.writeObject_entry");
    try {
    PixelGrabber grabber = new PixelGrabber(image, 0, 0, -1, -1, true);
    grabber.grabPixels();
    this.width = grabber.getWidth();
    this.height = grabber.getHeight();
    System.out.println("TransferImage.writeObject - width = " +width);
    System.out.println("TransferImage.writeObject - height = " +height);
    pix = grabber.getPixels();
    catch(InterruptedException ex) {
    throw new IOException("writeObject - ERROR: " +ex);
    System.out.println("TransferImage.writeObject_exit");
    * Reads the pix object and creates a BufferedImage from it.
    * @throws IOException
    public BufferedImage readObject() throws IOException {
    System.out.println("TransferImage.readObject_entry");
    try {
    int[] imgPix = (int[])pix;
    System.out.println("TransferImage.readObject - imgPixLength = " +imgPix.length);
    image = new BufferedImage(width, height, imageType);
    image.setRGB(0, 0, width, height, imgPix, 0, width);
    catch (Exception ex) {
    System.out.println("TransferImage.readObject - ERROR: " +ex);
    System.out.println("TransferImage.readObject_exit");
    return image;
    * Reads the pix object and returns an array of pixel bytes.
    * <p>
    * NOTE: Doesn't work
    * @throws IOException
    public byte[] readPix() throws IOException {
    System.out.println("TransferImage.readPix_entry");
    // Setup
    byte[] result = null;
    try {
    if(pix == null) throw new Exception("found null pix object");
    int[] imgPix = (int[])pix;
    int imgPixLen = imgPix.length;
    // Convert to bytes - this times out
    for(int i=0; i<imgPix.length; i++) {
    result = new byte[imgPixLen*4];
    int j, shift;
    for(j = 0, shift = 24; j < 4; j++, shift -= 8)
    result[i] += (byte)(0xFF & (imgPix[i] >> shift));
    if(result == null) throw new Exception("not able to read pix object");
    System.out.println("TransferImage.readPix - pixArrayLength = " +result.length);
    catch (Exception ex) {
    System.out.println("TransferImage.readPix - ERROR: " +ex);
    System.out.println("TransferImage.readPix_exit");
    return result;
    // Accessors
    * Gets the BufferedImage object.
    * @return
    public BufferedImage getImage() {
    return image;
    * Gets height of image in pixels.
    * @return
    public int getHeight() {
    return height;
    * Gets width of image in pixels.
    * @return
    public int getWidth() {
    return width;
    To use the class do this:
    //on client (for example)
    BufferedImage bufi = ImageIO.read(new File(<some_filePath>));
    TransferImage tbufi = new TransferImage(bufi, BufferedImage.TYPE_INT_BGR);
    //send tbufi to backend using something like a session bean and a transfer object
    //on backend reconstitute the buffered image
    TransferImage tbufi = spVO.getImage(); //spVO is my transfer object
    BufferedImage bufi = tbufi.readObject();
    I'd like to get readPix() working so that a byte array is returned which can feed directly into a ByteArrayInputStream, which can be useful for things like writing to a BLOB. So, if you figure out how to do that please share it.
    Take care,
    --BobC

Maybe you are looking for