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.

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);

  • 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 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

  • Why doesn't "include/object/text from file" work?

    I want to include (link) text from other Word documents to a  main  Word document and I use "include/object/text from file" (Word function)
    It works fine when I do so in "H:", but doing exactly the same in the Sharepoint environement result in "nothing" (nothing happens)
    It DOES work if I link from a document saved in Sharepoint to a "H:" - document, but that is of no use since I need all the documents to be stored in Sharepoint.
    Guess it has to do with the set up och Sharepoint.
    Greatful for any tips!

    Hi,
    Did you mean insert a object in the documents?
    Did you open the file with the local application or office web application?
    In the office web application, it doesn’t have the function to insert a object in the browser.
    I had tested with some word files in the library, open the word files with the local application, then insert file using the insert object function.
    It worked without any issue.
    What’s more, I had tested with Office 2010 and Office 2013, they all worked.
    Did the issue occur in other libraries? You can create a new library to check whether it works.
    You can also download a copy for the issued file, then open it in the local machine to check whether it works in the local machine.
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • Why cant I import M4V or FLV files into my I-Movie video? Please HELP!

    I just got the new Mac Desktop and REALLY hate that I cant drap and drop videos into the newer (i-Life11) -Imovie like I was used to since 2010. Seems to only work for photos. Is there a way around that?
    So I am making a church youth group video where I have spent HOURS trying to get parts of Youtube videos into the video to show them.  I have 2 forms saved on my desktop thanks to the software -   i have a FLV video and a M4V - both converted.  The Imovie already has plenty of clips that are M4V in them so I know it will take that form.  It just wont let me import them..they are there but are not accesible (they are 'faded') under the File/Import/Movies/Desktop  or File/Movies/RealPlayerDownloads.  They aren't darkened and  and I cant do anything with them.
    What am I doing wrong?
    HELP please.   Thanks for input. 
    Frustrated volunteer who has spent too many hours on this!!!
    Keri

    Use MPEG Streamclip to convert them to DV. In the case of the FLV file, this requires installing Perian.
    (71091)

  • Why cant i drag and drop mp3 files into my itunes library in itunes 11.1.1?

    I recently lost a hard drive with most of my music on it. i removed and reinstalled itunes and set it to work on my other hard drive. i was able to drag and drop mp3 files that i had and put them into my library. After the latest updates, now it only gives my the cirlcle with the slash though it when i try, not sure what changed

    did you manage to fix your problem.
    i tunes 6 used to be great for me but i upgraded to 7 which wiped my i tunes and ipod. im back to ver 6 now but i cant drag files from my c drive to any playlists

  • Append Objects to a ObjectOutput Stream

    i have opened a FileOutputStream(fis)(name,true) for appending and created a ObjectOutputStream with above fis. eventhough i am writing objects into file while reading i am only getting first object then i am getting StreamCorruptedException. why i am getting that exception and how to overcome my problem so that i can able to append object to existing file which holds objects?

    In the append mode, the file header is writted twice (it seems to be a bug...)...
    You must override the ObjectInputStream and the ObjectOutputStream to avoid the problem.
    public class MyObjectOutputStream extends ObjectOutputStream {
    public MyObjectOutputStream(OutputStream out) throws IOException {
    super(out);
    protected void writeStreamHeader() throws IOException {
    // Nothing in header
    public class MyObjectInputStream extends ObjectInputStream {
    public MyObjectInputStream(InputStream in) throws IOException, StreamCorruptedException{
    super(in);
    protected void readStreamHeader() throws IOException, StreamCorruptedException{
    // Nothing in header
    }

  • Why cant we put anything outside classes ?

    i couldnt think about any other title,as i am getting more and more confused.
    this is what i know :
    an object is "something" which has got some functionality && exists in memory (thats why real-world).
    why cant we create objects of "only" methods ?
    to be exact,i cant understand why java needs to put everything in the class?
    eg.
    public static void main(String args[])
    int i;
    i=i+5;
    this method should be able to form an object, it has got both data members, and it can call another function to modify the data.
    why do we NECESSARILY need to put this in a class ?

    paul.miner wrote:
    dpux wrote:
    i know its a design specification...but what advantage does it give ??
    josAH gave a valid point, but are there some others ?Old (current?) PHP is an example of what happens when you have a global namespace. Thousands upon thousands of functions with ugly names or stupid prefixes/suffixes ("real", "2", etc.). Static methods in a non-instantiable class are basically like creating namespaces for global methods.
    It's also much easier to find functions that belong together grouped in a class.True, but if "global functions" had been allowed in Java, I bet you a doughnut they would have used package names as a name space, in exactly the same way this is done with classes and interfaces.
    But again, idle speculation like this is a waste of time...

  • Why cant I open a PDF file from a cd-r that I burned into this cd myself at work on my personal laptop? I have the same version of Adobe.

    Why cant I open a PDF file from a cd-r that I burned into this cd myself at work on my personal laptop? I have the same version of Adobe.

    What happens when you try? Have you saved to your computer and then tried to open it?

  • Why cant poll a file more than once using File Adapter..

    Hi All,
    When we run webservice, as I am using File Adapter to read/write the file information.
    Usually, File Adapter reads once every file and it wont read again the same file whcih already red.
    Where and How this status maintained by File Adapter/BPEL in the system.
    Where this will be avvailable and why cant File Adapter read/poll the same file.
    Pls can any one of you share your ideas on the same.
    Thanks.

    Hi,
    Tried to get some information around where ftp adapter stores the timestamp but couldnt find anything useful.
    But we have a table for File adapter which captures the processing information (FILEADAPTER_IN )
    I dont have the setup for FTP adapter to run an example. If you could try the below we can clarify that the timestamp is not stored in memory.
    Configure as usual for a folder with a file pattern for FTP adapter.
    Drop a file to process it and then restart the SOA Suite and try to drop the same file with same timestamp to see wheather FTP adapter picks up or not.
    Ideally i feel once you restart the SOA Suite it should pick up the file, if still not picks up the file for second time then we need to dig indepth to see where this information is stored.
    btw what is your usecase ?
    Thanks,
    Vijay
    Edited by: veejai24 on 11-Apr-2012 03:43

  • How to read appended objects from file with ObjectInputStream?

    Hi to everyone. I'm new to Java so my question may look really stupid to most of you but I couldn't fined a solution by myself... I wanted to make an application, something like address book that is storing information about different people. So I decided to make a class that will hold the information for each person (for example: nickname, name, e-mail, web address and so on), then using the ObjectOutputStream the information will be save to a file. If I want to add a new record for a new person I'll simply append it to the already existing file. So far so good but soon I discovered that I can not read the appended objects using ObjectInputStream.
    What I mean is that if I create new file and then in one session save several objects to it using ObjectOutputStream they all will be read with no problem by ObjectInputStream. But after that if in a new session I append new objects they won't be read. The ObjectInputStream will read the objects from the first session after that IOException will be generated and the reading will stop just before the appended objects from the second session.
    The following is just a simple test it's not actual code from the program I was talking about. Instead of objects containing different kind of information I'm using only strings here. To use the program use as arguments in the console "w" to create new file followed by the file name and the strings you want save to the file (as objects). Example: "+w TestFile.obj Thats Just A Test+". Then to read it use "r" (for reading), followed by the file name. Example "+r TestFile.obj+". As a result you'll see that all the strings that are saved in the file can be successfully read back. Then do the same: "+w TestFile.obj Thats Second Test+" and then read again "+r TestFile.obj+". What will happen is that the strings only from the first sessions will be read and the ones from the second session will not.
    I am sorry for making this that long but I couldn't explain it more simple. If someone can give me a solution I'll be happy to hear it! ^.^ I'll also be glad if someone propose different approach of the problem! Here is the code:
    import java.io.*;
    class Fio
         public static void main(String[] args)
              try
                   if (args[0].equals("w"))
                        FileOutputStream fos = new FileOutputStream(args[1], true);
                        ObjectOutputStream oos = new ObjectOutputStream(fos);
                        for (int i = 2; i < args.length ; i++)
                             oos.writeObject(args);
                        fos.close();
                   else if (args[0].equals("r"))
                        FileInputStream fis = new FileInputStream(args[1]);
                        ObjectInputStream ois = new ObjectInputStream(fis);
                        for (int i = 0; i < fis.available(); i++)
                             System.out.println((String)ois.readObject());
                        fis.close();
                   else
                        System.out.println("Wrong args!");
              catch (IndexOutOfBoundsException exc)
                   System.out.println("You must use \"w\" or \"r\" followed by the file name as args!");
              catch (IOException exc)
                   System.out.println("I/O exception appeard!");
              catch (ClassNotFoundException exc)
                   System.out.println("Can not find the needed class");

    How to read appended objects from file with ObjectInputStream? The short answer is you can't.
    The long answer is you can if you put some work into it. The general outline would be to create a file with a format that will allow the storage of multiple streams within it. If you use a RandomAccessFile, you can create a header containing the length. If you use streams, you'll have to use a block protocol. The reason for this is that I don't think ObjectInputStream is guaranteed to read the same number of bytes ObjectOutputStream writes to it (e.g., it could skip ending padding or such).
    Next, you'll need to create an object that can return more InputStream objects, one per stream written to the file.
    Not trivial, but that's how you'd do it.

  • Cant write an image contained object to a file

    HI, I am trying to save Vector object to a file which contains an image as one element.But i am not able to do that can anybody tell how to write the program.
    i wrote the following program to do that task. but it's not working
    can anybody tell what changes i have to make my program to work properly
    my code as follows
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    class ImageWrit implements Serializable
    Image img;
    public ImageWrit(){
    img= Toolkit.getDefaultToolkit().getImage("a9.bmp");
    class A{
    public static void main(String s[])
    FileOutputStream fout;
    ObjectOutputStream out ;
    Vector list = new Vector();
    list.add(new ImageWrit());
    try{
    fout = new FileOutputStream("a.txt");
    out = new ObjectOutputStream(fout);
    out.writeObject(list);
    System.out.println("object is saved");
    catch(Exception e)
    System.out.println("error");
    }

    It's easier to read your code (and help) when you use the code tags in you message...
    it's also helpfull to know why you are not able to do it, compiler error, or runtime error, or...
    third it's best to show a StackTrace in case of an Exception, like thatcatch(Exception e)
        System.out.println("error"); // this tell nothing about the Exception
        e.printStackTrace();
    }Maybe your problem is that the Image returned by ToolKit is not Serializable, you can search the internet for something like "java serializable image" for some hints... like making an ImageIcon of the image, which will be Serializable
        public ImageWrit() {
            img = new ImageIcon(Toolkit.getDefaultToolkit().getImage("a9.bmp"));
        }(also have a look at javax.imageio.ImageIO)

  • Why cant i play wmv files in quick time x?

    why cant i play wmv files on quick time x?

    http://www.telestream.net/flip4mac-wmv/overview.htm
    They suggest QuickTime Player 7.6.6

  • Why cant I preview Project files in Outlook 2013 ?

    Why cant I preview Project files in Outlook 2013 ?

    Hello,
    Because there is no Outlook previewer available for MPP files. Typically Outlook only has previewers for default office applications.
    Paul
    Paul Mather | Twitter |
    http://pwmather.wordpress.com | CPS |
    MVP | Downloads

Maybe you are looking for

  • Pre-order shipment date changed??!!

    Can someone from Verizon please tell me why my preordered iphone is now showing it will be shipped in October, not delivered by 9/19 per my order and email confirmation? Please tell me this is a mistake? If you don't have the phones to ship as promis

  • Urgent HELP! need for my Zen touch (20

    Right here we go. I bought my zen touch online last year from a well known supplier. Absolutly brilliant mp3 plaey and happy with the value for money i got. The player did freee alot since i got it at inappropiate times eg. When i was on holiday and

  • Sound for Flash

    1. Which file formats are best for importing into CS3? 2. Is there any real benefit to importing stereo sound for files intended for web delivery? 3. Any suggestions for free programs for doing simple editing of sound files for CS3? Cutting, fade in

  • Templates for pages

    i am brand new to a Macbook Pro.  Where can i find templates for pages?  i need to write up a policy for daycare contract and wondering if they have templates like works or word does in window? TIA Terri ps, is there a site to learn how to use all th

  • HT201335 Is there a way to get airplay to work from iOS to my macbook without having to pay for a third-party application?

    Is there a way to get airplay to work from iOS to my macbook without having to pay for a third-party application? I've been trying to get my iPhone screen to play onto my macbook.