Appending Objects to a File using serialization

hi,
I was wondering if I can append objects in a single file. For example, suppose there are 2 .java files. 1st file creates the Serialized file caleed sl.dat, opens it, writes the object, close it down.
The 2nd file nw open that same file, sl.dat, in append mode, writes one more object and close it down.
next I want to read each object of the file. Will it work in this fashion?
I found a quite interesting discussion here. but it says that it is not possible.. is that true?
Any clue? Is there any other mean to achieve this?

arin wrote:
kajbj wrote:
I've done it by subclassing ObjectOutputStream. I could then add a constructor that took an argument that indicated if a header should be written or not.Can you explain what I need to done here... I have a class which extends ObjectOutputStream but what to do after that? What do u mean by header in the constructor?? Please help meYou do know that you have the source code for the class if you have a JDK? The source for ObjectOutputStream is in the src.zip.
The normal constructor calls writeStreamHeader, and that is the problem if you are going to append data since you don't want to get the stream header more than once. Create a constructor that takes a boolean as argument, and only calls writeStreamHeader if the boolean is true.
Kaj

Similar Messages

  • How to append Objects in a file.

    i have the following sample code ,
    its not read data properly and throws Stream Corrupted Exception in the appended record. ( at Last statement of try block ).
    Thanks,
    import java.io.*;
    public class IOError {
    public static void main(String[] args) {
    try {
    ObjectOutputStream oos = new ObjectOutputStream(
    new FileOutputStream("data.dat"));
    oos.writeObject(new String("string 1"));
    oos.writeObject(new String("string 2"));
    oos.flush();
    oos.close();
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.dat"));
    System.out.println("----- Round 1 Starts ---------");
    System.out.println((String) ois.readObject());
    System.out.println((String) ois.readObject());
    ois.close();
    ObjectOutputStream oos2 = new ObjectOutputStream(
    new FileOutputStream("data.dat",true)); // Appending Data
    oos2.writeObject(new String("string 3"));
    oos2.flush();
    oos2.close();
    ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("data.dat"));
    System.out.println("----- Round 2 Starts ---------");
    System.out.println((String) ois2.readObject());
    System.out.println((String) ois2.readObject());
    System.out.println((String) ois2.readObject()); // Stream Corrupted Exception
    catch(Exception e) {
    System.out.println(e);

    Nasty. When you open an ObjectOutputStream, it will write a few initializing bytes, so if you really want to append objects to a file, then after you read the first two strings, you need to create a new ObjectInputStream that will read those bytes.
    You could write an object indicating that now you are done with this ObjectOutputStream, so when you read the file and read this object, you know you have to create a new ObjectInputStream.
    oos.writeObject(new String("string 1"));
    oos.writeObject(new String("string 2"));
    oos.writeObject(null); // null could be used if you know you won't write any other null's in your code.
    //... append
    oos.writeObject(new String("string 3"));
    oos.writeObject(null);
    // read:
    FileInputStream fis = new FileInputStream("data.dat");
    ObjectInputStream ois2 = new ObjectInputStream(fis);
    String s;
    while ((s = (String)ois2.readObject()) != null) {
      System.out.println(s);
    ois2 = new ObjectInputStream(fis);
    while ((s = (String)ois2.readObject()) != null) {
      System.out.println(s);

  • Why cant i append objects to a file

    i'm amazed that i cannot append objects to a file
    as i did earlier in c++
    it gives StreamCorrupt error

    Ashutosh.options4u wrote:
    i'm amazed that i cannot append objects to a file
    as i did earlier in c++Whatever you did in C++ didn't involve ObjectOutputStream or Java Serialization. You can append anything but objects to a file in Java. The reasons are two:
    (a) ObjectOutputStream writes a header which ObjectInputStream expects to find at the beginning of the stream and nowhere else
    (b) closing an ObjectOutputStream and starting a new one to append to the same file breaks the specified semantics for preservation of object graphs under Serialization, which can only be implemented within a single instance of ObjectOutputStream.
    it gives StreamCorrupt errorI agree.

  • Appending objects in text file and searching.......

    I have been trieng to implement simple search operation on the class objects stored in the text file. but when i try to append new objects in the same file and search for the same; java.io.StreamCorruptedException is thrown. wat the problem is, that wen i append to the text file; it stores some header information before the actual object is stored and on the deserialization, this header information is causing the exception. the same header information is stored every time, i append to the file. anybody knws hw to get past it??? my code is as given below:
    package coding;
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.PrintWriter;
    import java.io.Serializable;
         class Employee implements Serializable{
              private static final long serialVersionUID = 1L;
              String name;
              int id;
              public int getId() {
                   return id;
              public void setId(int id) {
                   this.id = id;
              public String getName() {
                   return name;
              public void setName(String name) {
                   this.name = name;
              public Employee(String name, int id) {
                   this.name = name;
                   this.id = id;
         public class FileSearch{
         public static void main(String[] args) throws IOException
              /*Entering the records into the file*/
              Employee ob = null;
              File file=new File("c:\\abc.txt");
              InputStreamReader isr=new InputStreamReader(System.in);
              BufferedReader stdin=new BufferedReader(isr);
              char fileExist='y';
              if(file.exists())
                   System.out.println("File already exists!!!");
                   System.out.println("Append New Records(press y) Or Search Existing File(press any other button)?:");
                   String strTemp=stdin.readLine();
                   fileExist=strTemp.charAt(0);
              else
                   System.out.println("File doesnt exist; creating new file......");
              if(fileExist=='y')
                   FileOutputStream fos=new FileOutputStream(file,true);
                   ObjectOutputStream oos=new ObjectOutputStream(fos);
                   char choice='y';
                   System.out.println("Enter records:");
                   while(choice=='y')
                        System.out.println("enter id:");
                        String id_s=stdin.readLine();
                        int id=Integer.parseInt(id_s);
                        System.out.println("enter name:");
                        String name=stdin.readLine();
                        ob=new Employee(name,id);
                        try
                             oos.writeObject(ob);
                             //count++;
                             oos.flush();
                        catch(Exception e)
                             e.printStackTrace();
                        System.out.println("Enter more records?(y/n)");
                        String str1=stdin.readLine();
                        choice=str1.charAt(0);
                   oos.close();
              /*Searching for the record*/
              System.out.println("Enter Record id to be searched:");
              String idSearchStr=stdin.readLine();
              int idSearch=Integer.parseInt(idSearchStr);
              try
                   FileInputStream fis=new FileInputStream(
                             file);
                   ObjectInputStream ois=new ObjectInputStream(fis);
                   int flag=1;
                   FileReader fr=new FileReader(file);
                   int c=fr.read();
                   for(int i=0;i<c;i++)
                        Object ff=ois.readObject();
                        Employee filesearch=(Employee)ff;
                        if(filesearch.id==idSearch)
                             flag=0;
                             break;
                   ois.close();
                   if(flag==1)
                        System.out.println("Search Unsuccessful");
                   else
                        System.out.println("Search Successful");
              catch(Exception e)
                   e.printStackTrace();
    }

    966676 wrote:
    All what I need to elect by who this word repeated. But I don't know really how to make It, maybe LinkedListYou should choose the simplest type fullfilling your needs. In this case I'd go for <tt>HashSet</tt> or <tt>ArrayList</tt>.
    or I dont know, someone could help me?You need to introduce a variable to store the actual name which must be resetted if an empty line is found and then gets assigned the verry next word in the file.
    bye
    TPD

  • Appending, overwriting to a file, using BufferedWriter

    I have modify a file using BufferedWriter, plz suggest

    To append to a file with a BufferedWriter, use getBuffWriterForAppend(String filename)
        FileWriter fw = new FileWriter(filename, true);
        return new BufferedWriter(fw);
    } If you want to overwrite some of the contents, I think you need a RandomAccessFile. This doesn't appear to be usable with a BufferedWriter (unless you want to create a big wrapper - the BufferedWriter wrapping an OutputStreamWriter wrapping a PipedOutputStream which is connected to a PipedInputStream which has another thread reading from it and copying to the RandomAccessFile).
    Answer provided by Friends of the Water Cooler. Please inform forum admin via the
    'Discuss the JDC Web Site' forum that off-topic threads should be supported.

  • Appending Data in XML File using JAXB

    I need to write the 50,000 records into XML file. But at a time i need to write only 1000 records into XML. How do i append the data into XML using JAXB.

    I have tried but the data is written in the following way:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Users xmlns="http://www.yyyy.com/umc/importer/jaxb">
    <User id="101" xmlns="">
    <username>gjhs</username>
    <password>hdfhhdf</password>
    <role>df</role>
    <email>sdd</email>
    <phone>sdfdf</phone>
    <description>shkl</description>
    <property name="ernnker" value="hkdfhk"/>
    </User>
    </Users>
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Users xmlns="http://www.yyyy.com/umc/importer/jaxb">
    <User id="101" xmlns="">
    <username>gjhs</username>
    <password>hdfhhdf</password>
    <role>df</role>
    <email>sdd</email>
    <phone>sdfdf</phone>
    <description>shkl</description>
    <property name="ernnker" value="hkdfhk"/>
    </User>
    </Users>
    If i can eliminate the following lines from the above files then my job is done:
    </Users>
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Users xmlns="http://www.yyyy.com/umc/importer/jaxb">

  • Accessing objects of pdf file using javascript

    Is there a way, using javascript, to accsess objects that are defined in the pdf file, but where not defined using javascript.
    I would like for instance, to access a text stream, or any kind of stream using javascript.
    Thanks
    Moshe

    Not possible with Javascript.

  • Store and load objects to XML files using DOM

    Hello everybody,
    a quick question for all of you.
    I'm designing a desktop application which requires a lot of custom objects to be stored into XML files and later reloaded from them. I'm planning to use DOM, creating an interface like this:
    public interface StorableAsDom
    // Create an object from a DOM tree
    static Object createFromDom(org.w3c.dom.Node root) throws InvalidDomException;
    // Get the DOM tree for an object
    org.w3c.dom.DocumentFragment getDomTree(org.w3c.dom.Document doc) throws DOMException;
    Then, every class which needs to be saved should implement the above interface. This way everything works fine.
    My question is: do you know any available java package which already provides similar functionalities?
    I'd like not to reinvent the wheel if I can; time is always a critical factor.
    Thanks in advance to all of you.
    Cheers
    marcocaco

    Hi,
    When I need object -xml binding, I usually have two methods -
    one for reading & one for writing (the "VOs" below stands for "Value Objects" [getters/setters & empty constructor only]):
    READ: loadXML (= XML2VOs)
    1.XML2DOM - this method can be generic
    2.DOM2VOs - populate your VOs from the DOM just obtained in 1.
    WRITE: saveXML (=VOs2XML)
    1.VOs2DOM - create a new DOM document from your VOs' fields.
    2.DOM2XML - this method can be generic
    It would be nice (but dificult & not very elegant) to make DOM2VOs & VOs2DOM generic. If such methods will be written, they should be combined with the XML2DOM & DOM2XML (resp.) & then you would have two generic methods XML2VOs & VOs2XML... (Alternativelly, you can get Sun's JAXB package which does object-xml binding but this is not part of the JDK 5)
    If what I have outlined above sounds like what you want to do, let me know if you want more details (eg. how the DOM2VOs would be implemented etc)...

  • Append to remote FTP file using Pharlap

    Hi
    Currently a colleague of mine has managed to write data from our cFP 2020 to a remote file on an FTP server (using the FTP buffer VI in Labview 7.0). However there does not appear to be any way that he can append additional readings to that file. I would like to know if there is a way to append data to the remote FTP file. We are interested in storing 1 minute's worth of 3.3 second data within the remote file. Our SQL server will then import the flat file every minute into the database.
    So my question is, how can I append data readings from my cFP 2020 to remote files on an FTP server?
    --Thor

    Hi Thor,
    You’ll want to look into the NI LabVIEW Internet Toolkit that will allow you to programmatically send and retrieve files from a remote FTP server.
    Additionally, I have attached an example program to demonstrate how to send/retrive files programmatically using the FTP VIs. Note that you will need to have the Internet Toolkit in order to see the FTP VIs.
    Hope this helps. Thanks again.
    Kileen

  • Retreiving more than one object from an object stream using serialization.

    I have written a number of object into a file using the object Output stream. Each object was added separately with a button event. Now when I retrieve it only one object is being displayed. the others are not displayed The code for retrieval and inserting is given below. Please do help me.
    code for inserting is as follows
    Vehicle veh1 and vehicle class implements serializable
    veh1.vehNum=tf1.getText();
              veh1.vehMake=tf2.getText();
              veh1.vehModel=tf3.getText();
              veh1.driveClass=tf4.getText();
              veh1.vehCapacity=tf5.getText();          
              FileOutputStream out = new FileOutputStream("vehicle.txt",true);
              ObjectOutputStream s = new ObjectOutputStream(out);
              s.writeObject(veh1);
    retrieval
    FileInputStream out = new FileInputStream("vehicle.txt");
              String str1,str2;
              str1=str2=" ";
              Vehicle veh=new Vehicle();
              ObjectInputStream s = new ObjectInputStream(out);
              try
              Vehicle veh1=(Vehicle)s.readObject();
              s.close();
              int i=0;
              str1=veh1.vehNum;
              str2+=str1+"\t";
              str1=veh1.vehMake;
              str2+=str1+"\t";
              str1=veh1.vehModel;
              str2+=str1+"\t";
              str1=veh1.driveClass;
              str2+=str1+"\t";
              str1=veh1.vehCapacity;
              str2+=str1+"\t\n";
              ta1.append(str2);
              catch(Exception e)
              e.printStackTrace();
    Pleas give me the code for moving through the object until it reaches the end of file

    You can read objects from the stream one by one. So, what you need is an endless loop like this:
    // Suppose you have an ObjectInputStream called objIn
    // So here is the loop which reads objects from the stream:
    Object inObj;
    while (1) {
        try {
            inObj=objIn.readObject();
            // Do something with the object we got
            parse_the_object(inObj);
        } catch (EOFException ex) {
            // The EOFException will be thrown when
            // we reached the end of the file, so here we break out
            // of our lovely infinite cycle
            break;
        } catch (Exception ex) {
            ex.printStackTrace();
            // Here you may decide what to do...
            // Probably the processing will end here, too. For now,
            // we moving on, hoping there is still something to read
    objIn.close();
    // ...

  • Appending XML data to a file using file adaptor

    Hi,
    I am trying to append data to a file using file adaptor in XML format. (Objective is to store data as XML message in the file). I understand it is possible to append data to an existing file by making appropriate changes in WSDL manually. However, my issue is every time the XML data is appended to a file even the XML header message is also getting appended. As a result the file data does not adhere to defined schema structure anymore.
    Is there a way to save XML data in a file in append mode ?
    Thanks, Riz

    I am having the same issue as well, which makes the output XML an invalid one. I have an XSD that has a hierarchy of elements. whenever I am wiriting the child elements the header message & the name space is also getting written. For example
    <?xml version="1.0" ?><Parent xmlns="http://testSchema.com/outputSchema">
    <StartDate>01/01/2001</StartDate>
    <EndDate>01/30/2001</EndDate>
    <Child/>
    </Parent>
    <?xml version="1.0" ?><Child xmlns:ns1="http://testSchema.com/outputSchema">
    <ns1:Id>20012981</ns1:Id>
    <ns1:Value/>
    <ns1:Date>01/15/2001</ns1:Date>
    </Child>
    <?xml version="1.0" ?><Child xmlns:ns1="http://testSchema.com/outputSchema">
    <ns1:Id>20012981</ns1:Id>
    <ns1:Value/>
    <ns1:Date>01/15/2001</ns1:Date>
    </Child>
    I am using a onefile adapter partnerlink to write the parent & an another one for writing the child element, since the child elements will repeat more than once. One other way to fix this issue is write the data using java embedded activity, but that would need a lot of boiler plate code, for writing/reading/appending the same file & for handling all those IOexceptions & buffer IN/outs. I am curious if someone had the same issue & how they resolved it.

  • Append in same file using GUI_DOWNLOAD file type is pdf

    Hi All
    I have three internal tables and want to append in same  pdf file using GUI_DOWNLOAD . My problem is this when i m using the same file it overwrites it i also mark APPEND = 'X' . Can anybody help me how can i append.
    Thanks
    Viki

    Hi
    Try
    http://help.sap.com/saphelp_nw04/helpdata/en/60/f8123e9c6c498084f9f2bafab32671/content.htm
    /people/sap.user72/blog/2004/11/10/bsphowto-generate-pdf-output-from-a-bsp
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/c2567f2b-0b01-0010-b7b5-977cbf80665d
    https://www.sdn.sap.com/irj/sdn?rid=/webcontent/uuid/24b9e126-0b01-0010-e098-f46384fad9f3 [original link is broken]
    Regards
    Raj

  • Can I append date to the file name using Bursting

    Hi All,
    I know that we can append date to the file using %y, %m and %d for
    Email
    FTP
    WEBDAV
    But is there any way of appending the date to the file name if I am bursting my file to a shared location.
    I tried that %y, %m and %d but that doesn't work for bursting.
    Please reply
    Thanks,
    Ronny

    If this requirment is for EBS, please refer the following blog
    http://blogs.oracle.com/BIDeveloper/2010/08/xdoburstrpt_passing_parameters.html
    For standalone see the following delivery sql query as example.
    select
    d.department_name KEY,
    'Standard' TEMPLATE,
    'RTF' TEMPLATE_FORMAT,
    'en-US' LOCALE,
    'PDF' OUTPUT_FORMAT,
    'FILE' DEL_CHANNEL,
    'C:\Temp' PARAMETER1,
    d.department_name||'_'||to_char(sysdate,'mmddyyyy')|| '.pdf' PARAMETER2
    from
    departments d
    Thanks
    Ashish

  • Append data into the file in application server

    Hi Friends,
    I have an issue where i have a job which has three different stepst for same program. If i run the job the program will create a file in the application server and append the other two steps in the same file without overwriting the file or creating a new file.
    My problem is like its creating three different files in application server for that particular job since it has three steps . Its not appending into one particular file .
    I am using the FM 'Z_INTERFACE_FILE_WRITE' where i have used the pi_append in the exportng parameter . ITs working when i specify the file in local system. It is appending correctly when i run the report normally to apppend into local system.
    But when i schedule a job to append the file in application server its creating three different files.
    Kindly help me if anyone is aware of this issue
    Thanks in advance
    Kishore

    Hi,
    Please use open dataset to write and append files.Please check the logic of Z FM which you are using .
    To open and write into a file  use
    OPEN DATASET FNAME FOR OUTPUT.
    To append data into existing file use
    OPEN DATASET FNAME FOR APPENDING.
    To write into file:
    v_file = file path on application server
      OPEN DATASET v_file FOR output.
      IF sy-subrc NE 0.
    write:/ 'error opening file'.
      ELSE.
       TRANSFER data TO v_file.
      ENDIF.
    CLOSE DATASET v_file.
    For appending :
    OPEN DATASET v_file fOR APPENDING.(file is opened for appending data  position is set to the end of the file).
    Thanks and Regards,
    P.Bharadwaj

  • How to continue to read Object from a file?

    At some program I write an object into a file. This program will be called again and again so that there are many objects which are saved to that file. And I write another program to read object from this file. I can read the first object but can not read the second. However if I delete the object in that file (using editplus, by manually) I can read the second. Because now the second object is the first object. (Delete first object).
    The exception when I read the second object is below:
    java.io.StreamCorruptedException: Type code out of range, is -84
         at java.io.ObjectInputStream.peekCode(ObjectInputStream.java:1607)
         at java.io.ObjectInputStream.refill(ObjectInputStream.java:1735)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:319)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:272)
         at LogParser.main(LogParser.java:42)
    Exception in thread "main" The read object from file program is below:
         public static void main(String[] args) throws Exception {
            FileInputStream fis = new FileInputStream(path + File.separator + "ErrorApp21config2.log");
            ObjectInputStream ois = new ObjectInputStream(fis);
            ErrorLog errorLog = (ErrorLog)ois.readObject();
            System.out.println(errorLog.getErrorDate());
            FIFData fifData = (FIFData)errorLog.getErrorDescription();
            CommRegistration commRegistration = (CommRegistration)
                                     fifData.getDataObject(FIFData.REGISTRATION_DATA);
            String ic = commRegistration.getPatient().getPatExtID();
            System.out.println(ic);
            CommQueue commQueue = (CommQueue) fifData.getDataObject(FIFData.QMS_DATA);
            String location = commQueue.getLocation();
            System.out.println(location);
            ois.readObject();  //will throw above exception
            fis.close();
         }Can anyone tell me how to continue to read object? Or I should do some special things when I write object into file?

    Thanks Jos.
    Perhaps you are correct.
    There are some code in a SessionBean to log an object. Write file code is below.
         private void logPreRegError(
              byte[] strOldFifData,
            byte[] strNewFifData,
              String requestID)
              throws TTSHException {
              if (requestID.equals(RequestConstants.ADMIT_PATIENT)){
                String runtimeProp = System.getProperty("runtimeproppath");
                FileOutputStream fos = null;
                   try {
                        fos = new FileOutputStream(
                            runtimeProp + File.separator + "Error.log", true);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    bos.write(strOldFifData);
                    bos.write(strNewFifData);
                    bos.flush();
                   } catch (FileNotFoundException e) {
                        log(e);
                   } catch (IOException e) {
                    log(e);
                   } finally{
                    if (fos != null){
                             try {
                                  fos.close();
                             } catch (IOException e1) {
                                  log(e1);
         }strOldFifData and strNewFifData are the byte[] of an object. Below is the code to convert object to byte[].
         private byte[] getErrorData(FIFData fifData, boolean beforeException, String requestID) {
            ErrorLog errorLog = new ErrorLog();
            errorLog.setErrorDate(new Date());
            errorLog.setErrorDescription(fifData);
            errorLog.setErrorModule("Pre Reg");
            if (beforeException){
                errorLog.setErrorSummary("RequestID = " + requestID +" Before Exception");
            }else{
                errorLog.setErrorSummary("RequestID = " + requestID +" After Exception");
              ByteArrayOutputStream baos = null;
              ObjectOutputStream oos = null;
              byte[] bytErrorLog = null;
              try {
                  baos = new ByteArrayOutputStream();
                   oos = new ObjectOutputStream(baos);
                  oos.writeObject(errorLog);
                  oos.flush();
                  bytErrorLog = baos.toByteArray();
              } catch (IOException e) {
                   log(e);
              } finally {
                if (baos != null){
                        try {
                             baos.close();
                        } catch (IOException e1) {
                             log(e1);
              return bytErrorLog;
         }I have two questions. First is currently I have got the log file generated by above code. Is there any way to continue to read object from log file?
    If can't, the second question is how to write object to file in such suitation (SessionBean) so that I can continue to read object in the future?

Maybe you are looking for