Writing java object into file

Dear Experts,
What is the best way to write java objects into file
1. Using Object Output Stream
or
2.Using ByteArray OutputStream
with Thanks
Panneer

Dear Experts,
What is the best way to write java objects into file
1. Using Object Output Stream
or
2.Using ByteArray OutputStream
with Thanks
PanneerWhat do you mean or? Because I would assume the contents of the byte array stream is coming from an ObjectOutputStream.
Or do you mean to use some sort of buffering...

Similar Messages

  • API for converting a Java object into XML?

    Do you know of any Java API that I could use to convert a Java
    object into its equivalent XML representation?
    For example if I have a class called "Foo" with variables va, vb
    and I have an instance of Foo with va having the value 1 and vb
    having the value 2, I would like be able to generate the
    following XML fragment:
    <Foo>
    <va>1</va>
    <vb>2</vb>
    </Foo>
    Thanks,
    -- Rob
    null

    Rob Tan (guest) wrote:
    : Do you know of any Java API that I could use to convert a Java
    : object into its equivalent XML representation?
    : For example if I have a class called "Foo" with variables va,
    vb
    : and I have an instance of Foo with va having the value 1 and
    vb
    : having the value 2, I would like be able to generate the
    : following XML fragment:
    : <Foo>
    : <va>1</va>
    : <vb>2</vb>
    : </Foo>
    : Thanks,
    : -- Rob
    There is none that I know of.
    Oracle XML Team
    http://technet.oracle.com
    Oracle Technology Network
    null

  • Storing Java objects into a Derby db

    Hi, Im new to Apache Derby, Id like to know how store a Java Object into a db field.
    Im working with the JPCap library and the Packet class has many attributes and values, it will be easier if I could save the complete object in a just one field.
    Thanks in advantage.

    DB script:
    "Create Table APP.PACKETS (ID INTEGER not null primary key, PACKET LONG VARCHAR FOR BIT DATA)"
    Test:
    import jpcap.packet.TCPPacket;
    import java.io.ByteArrayOutputStream;
    import java.io.ObjectOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.ObjectInputStream;
    import java.io.IOException;
    private static int increment;
    public static void addPacket() {
    System.out.println("Inserting...");
    TCPPacket packet = new TCPPacket(12, 8080, 56, 78, false, false, false, false, true, true, true, true, 10, 10);
    try {
    ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
    ObjectOutputStream objOutStream = new ObjectOutputStream(byteOutStream);
    objOutStream.writeObject(packet);
    objOutStream.flush();
    objOutStream.close();
    byteOutStream.close();
    PreparedStatement pstmt = conn.prepareStatement("Insert Into APP.PACKETS Values(?, ?)");
    pstmt.setInt(1, ++increment) ;
    pstmt.setBytes(2, byteOutStream.toByteArray());
    pstmt.execute();
    conn.commit() ;
    System.out.println("Inserted!");
    } catch(IOException e) {
    e.printStackTrace();
    } catch(SQLException e) {
    e.printStackTrace();
    public static void showPackets() {
    String query = "Select * From APP.PACKETS ";
    Statement st = null;
    ResultSet rs = null;
    int id = -1;
    byte[] data = null;
    try {
    st = conn.createStatement();
    rs = st.executeQuery(query);
    while (rs.next()) {
    id = rs.getInt("id") ;
              data = rs.getBytes("packet") ;
    ByteArrayInputStream byteInStream = new ByteArrayInputStream(data);
    ObjectInputStream objInStream = new ObjectInputStream(byteInStream);
    Object obj = objInStream.readObject();
    objInStream.close();
    byteInStream.close();
    if (obj instanceof TCPPacket) {
    TCPPacket p = (TCPPacket)obj;
    System.out.println(p.dst_port); // Print anything
    } else {
    System.out.println("No Found!");
    } catch(IOException e) {
    e.printStackTrace();
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch(SQLException e) {
    e.printStackTrace();
    Thats one of several ways to insert Java Objects...

  • How to convert Java Objects into xml?

    Hello Java Gurus
    how to convert Java Objects into xml? i heard xstream can be use for that but i am looking something which is good in performance.
    really need your help guys.
    thanks in advance.

    There are apparently a variety of Java/XML bindings. Try Google.
    And don't be so demanding.

  • JAXB - Marshalling populated Java object into XML

    I have a populated Java object that I'd like to marshall to an xml file.
    I don't instantiate this object from a DTD, nor do I need to generate the object via unmarshalling an xml. I'm just trying to build something akin to a toXML() method for this object.
    Is JAXB what I should be using?
    Any suggestions?
    Thanks a lot.
    Paul

    Hi Paul,
    Did you ever sort this out?
    I too am now having problems with Marshalling to and from XML.
    I have been able to write my own Marshalling class but can't seem to be able to DeMarshal a XML stream to a SOAP object.
    Please reply to this message if you are able to maybe shed some light on my problem.
    I have a populated Java object that I'd like to
    marshall to an xml file.
    I don't instantiate this object from a DTD, nor do I
    need to generate the object via unmarshalling an xml.
    I'm just trying to build something akin to a toXML()
    method for this object.
    Is JAXB what I should be using?
    Any suggestions?
    Thanks a lot.
    Paul

  • How to pass the java object into the spring controller

    Hi Friends
    When I hit the url at the first time my call goes to the spring controller and sets the userDetails objects in the modelAndView.addObject("userDetails", userDetails.getUserDetails()) and returns the userDetails.html page. if I click any link in the same page i want to pass same (userDetails) object thru javascript or jquery and calls the another(controller) method and returns the same (userDetails.html) page.
    It means how can i pass the java object thru javascript or jquery and calls the controller. if i get the same object in my controller i can avoid calling the db again. please help me out to resolve this issue. i am tired of fixing this issue.
    Regards
    Sherin Pooja

    If you want to avoid calling the database again then cache the data.
    However before you do that make sure that calling the database, in the context of YOUR system, is going to be an actual problem.
    For example there is absolutely no point in caching a  User object when only one user an hour is actually using the system.

  • Blaze DS - Mapping java object into another java application

    Good afternoon,
    I realized a Client-Server application. Server is Java-based. Client is Flex. Server services are accessible through Blaze DS.
    Now I have some Java clients that need to access server services. Blaze DS permits to do it simply but I don't know how to map java objects as I do using [RemoteClass(alias.....)] construct at Actionscript side.
    For example, server sends a MyObjectType and client receives an ASObject.
    Is there a way to map java MyObjectType automatically at destination?
    Thank you for help and sorry for poor english.
    Regards, Francesco

    xstream will convert any given java object to xml. Not sure what support it offers for schemas.
    http://xstream.codehaus.org/

  • Emergency! Writing an object into a file (NotSerializableException)

    Hi, I am now working in a project. I came across a serialization problem which I am spending so many days and haven't gotten any solution.
    I assume that the problem is caused by the complexity of class design in a package. The saved object extends all of 9~11 classes in which some are abstract class, some are listening interface class, some are just normal class but extending from GUI components such as JTree, JFrame and so on. Besides static is spred over anywhere in the classes.
    code:(No problem here)
    output = new ObjectOutputStream( new eFileOutputStream( fileName ) );
    output.writeObject(prj);
    output.flush();
    Futher, the 'prj' object is proved to be very serializable as a result of "isSerializable()" function before writting in to a file. However it invokes IOExceptions, isn't it funny?
    ex:
    A--B--C--D--E
    |
    |
    F G H
    | |
    I J
    |
    prj
    In the example of above, is it possible to store all the state of objects A to J by storing prj so that I can re-construct the whole of objects relations and the members in them from the stored 'prj'?
    Back to the original problem, then...
    Do I have to get rid of all the static declarations of parent classes?
    Do I have to serialize each single classes one by one without being greedy tryint to store all of the state of objects linked to 'prj' at once?
    Do I have to get every single objects implemented 'Serializable' including abstruct and interface classes if they contains static declaration or someting unserializable?
    Please give me any help or hint, anything I am appreciate for.

    The problem is not very clear. Some code snippets might help. Especially the Exception details.Your object graph is somewhat confusing too.
    To answer your questions, the default Serialization (where the object prj, though extends java.io.Serializable, DOESN'T implement writeObject() and readObject() methods) will succeed only if all the reachable super classes in the graph are a. either implement Serializable or b. have no-argument constructors. In case of b., it's the responsibility of the object prj to re-establish the state of the parent classes from the serialized stream. You can do that by implementing writeObject() and readObject() methods themselves.
    The transient and static fields are never serialized. So if you want to preserve the value of a static field then you'll have to either a. explicitly serialize that field out to the ObjectOutputStream and read it back from the ObjectInputStream in the writeObject() and readObject() methods or b. using reflection where you can get the Class name and get the static field value from the corresponding 'Class' data type also using reflection (object.getClass().getField("fieldName").getValue(null)).

  • Java Array into File Output

    Hello,
    I have a working program that normally, I hand-wire the information into the file and it is stored in an array and I work with it till the end of the program. This is where the problem is coming from.
    Now the document will be in an external file, and the informations needed for the program should be read from the external file;
    At the beginning of the program, the input file will be loaded into the program and the file will be saved at the end of the program. Giving room for editing / adding to the file during program run and at the end save all the information back into same external file.
    Please how am I to go about this? I really need help in here....
    Thanks for your help in advance.
    Regards

    Please don't post the same question in multiple forums. I'm locking this thread as the question seems more appropriate to "New to Java".

  • Writing java objects to a pipe

    Hi to all,
    I am trying to write a record object to a pipe in a class implementing a interface pipeInput.Now the record object gets the data from a text file and then i write this object to a pipe .I want the object to be written in a pipe in xml form.In case if multiple record object to be copied to a pipe or until all the record objects are written to the file what i have to do.
    thanking you in advance
    yash

    first, this doesn't sound like an xml issue try posting in the general forum. But second, do you have a specific question. You've just listed (badly) what you want to do.

  • Serializing Java Objects to XML files

    Hi,
    We looking for SAP library which can serialize Java Objects into XML files.
    Can you point us were to find it ?
    We have found such open source library called "XStream" at the following link
    http://www.xml.com/pub/a/2004/08/18/xstream.html
    Is it allowed to use that library inside SAP released software ?
    Thanks
    Orit

    How about https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/webcontent/uuid/83f6d2fb-0c01-0010-a2ba-a2ec94ba08f4 [original link is broken] [original link is broken]? Depends on your use cases...
    Both are supported in SAP NW CE 7.1.
    HTH!
    -- Vladimir

  • How to write into file from xml dom Object

    Hello,
    I try to transform my xml DOM document object into
    file. I try the following:
    try {
              // Prepare the DOM document for writing
              DOMSource source = new DOMSource(newDoc);
              // Prepare the output file
              File file = new File(myHomeRep + "btLom.xml");
              StreamResult result = new StreamResult(file);
              // Write the DOM document to the file
              Transformer xformer = TransformerFactory.newInstance().newTransformer();
              xformer.transform(source, result);
              } catch (TransformerConfigurationException e) {
              } catch (TransformerException e) {
    But my file is empty.
    I do it with some wel formed xml tree document, thus I am certain
    that the xml tree exists.
    Could you explane me please what I am doeing wrong,
    or is there are some possibility to make from my xml dom object
    a file.
    In advance much thanks,
    Julia

    Here's one thing you are doing wrong:} catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    }With this code, if an exception occurs then you are guaranteed to know nothing about it. At the minimum do this:} catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }

  • How can I use XStream to persist complicated Java Object  to XML & backward

    Dear Sir:
    I met a problem as demo in my code below when i use XTream to persist my Java Object;
    How can I use XStream to persist complicated Java Object to XML & backward??
    See
    [1] main code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import com.thoughtworks.xstream.XStream;
    import com.thoughtworks.xstream.io.xml.DomDriver;
    public class PhoneList {
         ArrayList<PhoneNumber> phones;
         ArrayList<Person> person;
         private PhoneList myphonelist ;
         private LocationTest location;
         private PhoneList(String name) {
         phones = new ArrayList<PhoneNumber>();
         person = new ArrayList<Person>();
         public ArrayList<PhoneNumber> getphones() {
              return phones;
         public ArrayList<Person> getperson() {
              return person;
         public void addPhoneNumber(PhoneNumber b1) {
              this.phones.add(b1);
         public void removePhoneNumber(PhoneNumber b1) {
              this.phones.remove(b1);
         public void addPerson(Person p1) {
              this.person.add(p1);
         public void removePerson(Person p1) {
              this.person.remove(p1);
         public void BuildList(){
              location = new LocationTest();
              XStream xstream = new XStream();
              myphonelist = new PhoneList("PhoneList");
              Person joe = new Person("Joe, Wallace");
              joe.setPhone(new PhoneNumber(123, "1234-456"));
              joe.setFax(new PhoneNumber(123, "9999-999"));
              Person geo= new Person("George Nixson");
              geo.setPhone(new PhoneNumber(925, "228-9999"));
              geo.getPhone().setLocationTest(location);          
              myphonelist.addPerson(joe);
              myphonelist.addPerson(geo);
         public PhoneList(){
              XStream xstream = new XStream();
              BuildList();
              saveStringToFile("C:\\temp\\test\\PhoneList.xml",convertToXML(myphonelist));
         public void saveStringToFile(String fileName, String saveString) {
              BufferedWriter bw = null;
              try {
                   bw = new BufferedWriter(
                             new FileWriter(fileName));
                   try {
                        bw.write(saveString);
                   finally {
                        bw.close();
              catch (IOException ex) {
                   ex.printStackTrace();
              //return saved;
         public String getStringFromFile(String fileName) {
              BufferedReader br = null;
              StringBuilder sb = new StringBuilder();
              try {
                   br = new BufferedReader(
                             new FileReader(fileName));
                   try {
                        String s;
                        while ((s = br.readLine()) != null) {
                             // add linefeed (\n) back since stripped by readline()
                             sb.append(s + "\n");
                   finally {
                        br.close();
              catch (Exception ex) {
                   ex.printStackTrace();
              return sb.toString();
         public  String convertToXML(PhoneList phonelist) {
              XStream xstream = new  XStream(new DomDriver());
              xstream.setMode(xstream.ID_REFERENCES) ;
              return xstream.toXML(phonelist);
         public static void main(String[] args) {
              new PhoneList();
    }[2].
    import java.io.Serializable;
    import javax.swing.JFrame;
    public class PhoneNumber implements Serializable{
           private      String      phone;
           private      String      fax;
           private      int      code;
           private      String      number;
           private      String      address;
           private      String      school;
           private      LocationTest      location;
           public PhoneNumber(int i, String str) {
                setCode(i);
                setNumber(str);
                address = "4256, Washington DC, USA";
                school = "Washington State University";
         public Object getPerson() {
              return null;
         public void setPhone(String phone) {
              this.phone = phone;
         public String getPhone() {
              return phone;
         public void setFax(String fax) {
              this.fax = fax;
         public String getFax() {
              return fax;
         public void setCode(int code) {
              this.code = code;
         public int getCode() {
              return code;
         public void setNumber(String number) {
              this.number = number;
         public String getNumber() {
              return number;
         public void setLocationTest(LocationTest bd) {
              this.location = bd;
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(location);
            f.getContentPane().add(location.getControls(), "Last");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
         public LocationTest getLocationTest() {
              return location;
         }[3].
    package test.temp;
    import java.io.Serializable;
    public class Person implements Serializable{
         private String           fullname;
           @SuppressWarnings("unused")
         private PhoneNumber      phone;
           @SuppressWarnings("unused")
         private PhoneNumber      fax;
         public Person(){
         public Person(String fname){
                fullname=fname;           
         public void setPhone(PhoneNumber phoneNumber) {
              phone = phoneNumber;
         public void setFax(PhoneNumber phoneNumber) {
              fax = phoneNumber;
         public PhoneNumber getPhone() {
              return phone ;
         public PhoneNumber getFax() {
              return fax;
        public String getName() {
            return fullname ;
        public void setName(String name) {
            this.fullname      = name;
        public String toString() {
            return getName();
    }[4]. LocationTest.java
    package test.temp;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class LocationTest extends JPanel implements ChangeListener
        Ellipse2D.Double ball;
        Line2D.Double    line;
        JSlider          translate;
        double           lastTheta = 0;
        public void stateChanged(ChangeEvent e)
            JSlider slider = (JSlider)e.getSource();
            String name = slider.getName();
            int value = slider.getValue();
            if(name.equals("rotation"))
                tilt(Math.toRadians(value));
            else if(name.equals("translate"))
                moveBall(value);
            repaint();
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(ball == null)
                initGeom();
            g2.setPaint(Color.green.darker());
            g2.draw(line);
            g2.setPaint(Color.red);
            g2.fill(ball);
        private void initGeom()
            int w = getWidth();
            int h = getHeight();
            int DIA = 30;
            int padFromEnd = 5;
            line = new Line2D.Double(w/4, h*15/16, w*3/4, h*15/16);
            double x = line.x2 - padFromEnd - DIA;
            double y = line.y2 - DIA;
            ball = new Ellipse2D.Double(x, y, DIA, DIA);
            // update translate slider values
            int max = (int)line.getP1().distance(line.getP2());
            translate.setMaximum(max);
            translate.setValue(max-padFromEnd);
        private void tilt(double theta)
            // rotate line from left end
            Point2D pivot = line.getP1();
            double lineLength = pivot.distance(line.getP2());
            Point2D.Double p2 = new Point2D.Double();
            p2.x = pivot.getX() + lineLength*Math.cos(theta);
            p2.y = pivot.getY() + lineLength*Math.sin(theta);
            line.setLine(pivot, p2);
            // find angle from pivot to ball center relative to line
            // ie, ball center -> pivot -> line end
            double cx = ball.getCenterX();
            double cy = ball.getCenterY();
            double pivotToCenter = pivot.distance(cx, cy);
            // angle of ball to horizon
            double dy = cy - pivot.getY();
            double dx = cx - pivot.getX();
            // relative angle phi = ball_to_horizon - last line_to_horizon
            double phi = Math.atan2(dy, dx) - lastTheta;
            // rotate ball from pivot
            double x = pivot.getX() + pivotToCenter*Math.cos(theta+phi);
            double y = pivot.getY() + pivotToCenter*Math.sin(theta+phi);
            ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
            lastTheta = theta;  // save theta for next time
        private void moveBall(int distance)
            Point2D pivot = line.getP1();
            // ball touches line at distance from pivot
            double contactX = pivot.getX() + distance*Math.cos(lastTheta);
            double contactY = pivot.getY() + distance*Math.sin(lastTheta);
            // find new center location of ball
            // angle lambda = lastTheta - 90 degrees (anti-clockwise)
            double lambda = lastTheta - Math.PI/2;
            double x = contactX + (ball.width/2)*Math.cos(lambda);
            double y = contactY + (ball.height/2)*Math.sin(lambda);
            ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
        JPanel getControls()
            JSlider rotate = getSlider("rotation angle", "rotation", -90, 0, 0, 5, 15);
            translate = getSlider("distance from end",  "translate", 0, 100, 100,25, 50);
            JPanel panel = new JPanel(new GridLayout(0,1));
            panel.add(rotate);
            panel.add(translate);
            return panel;
        private JSlider getSlider(String title, String name, int min, int max,
                                  int value, int minorSpace, int majorSpace)
            JSlider slider = new JSlider(JSlider.HORIZONTAL, min, max, value);
            slider.setBorder(BorderFactory.createTitledBorder(title));
            slider.setName(name);
            slider.setPaintTicks(true);
            slider.setMinorTickSpacing(minorSpace);
            slider.setMajorTickSpacing(majorSpace);
            slider.setPaintLabels(true);
            slider.addChangeListener(this);
            return slider;
    }OK, My questions are:
    [1]. what I generated XML by XSTream is very complicated, especially for object LocationTest, Can we make it as simple as others such as Person object??
    [2]. after I run it, LocationTest will popup and a red ball in a panel will dsiplay, after I change red ball's position, I hope to persist it to xml, then when I read it back, I hope to get same picture, ie, red ball stiil in old position, How to do that??
    Thanks a lot!!

    Positive feedback? Then please take this in a positive way: if you want to work on persisting Java objects into XML, then GUI programming is irrelevant to that goal. The 1,000 lines of code you posted there appeared to me to have a whole lot of GUI code in it. You should produce a smaller (much smaller) example of what you want to do. Calling the working code from your GUI program should come later.

  • Sending Java object using E-Mail

    Dear Experts,
    In my application I am trying write java Object in a file. Then I have to attach that file with an E-Mail. In the receiver side I have to download the file and read the Java Object from file.
    The Problem is , when I am sending and receiving mail using outlook Express, My file is reduced by some Kbs(Example , I am sending 66kb but I am receiving only 64Kb).
    If any of you have some ideas to solve the above problem, please let me know.
    With Thanks
    Panneer

    Perhaps you are trying to send binary but e-mail must be in text or the data will get filtered/mangled.

  • About Java Object ???

    Hi..,,
    I have a general question ? Is it possible to read a java object into R/3(not using WAS or EP ).
    If there is any, Please let me know..
    Thanks

    Sunil,
    I am not sure what exactly you are looking for. Can you explain?
    Regards,
    Ravi

Maybe you are looking for

  • How can we assign an action triggered by an event to a Background job?

    Hi All,         At the moment we are having an on click action event "EXECUTE"  [GSACTIONS/ActionOV ->eh_onexecute] , on click of this event , it is triggering a BADI which has a rewritten method "IF_EX_EXEC_METHODCALL_PPF~EXECUTE" in which we have o

  • Setting the source-interface in a tcl script for email.

    So once again I am trying to figure this out and failing miserably. The only thin I can think of at the moment is that I need to tell it to source from a specific vrf interface. I've tried looking through possible enviornment variables. Hoping I coul

  • Final Cut Express HD update on cd?

    Recently bought imac g5 isight. Couldn't get final cut express HD to work as it did not recognise the PCI card. Apple provide an update to fix this but it must be downloaded via the net. Can i not acquire this somehow on disk from apple as i am using

  • Find technical name of receiving query in RSBBS assignment

    Dear Experts, under transaction RSBBS one can assign sender/receiver details. While the technical name of both sender and receiver are entered when createing the RRI, one can only retrieve a compressed ID (i.e. 46F28FNV1L4H1QENI1KKEKWUCAZPAOPRD) for

  • Permanent deletion

    i like the idea of time machine. but once in a while i want to get delete something without backing it up. how do i permanently delete one or more files (adult films, financial statements, adult films) but still have time machine back up the rest of