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

Similar Messages

  • How to append records in a file, through file adapter.

    Hi All,
    How to append records in a file, through file adapter.
    I have to read data from database and need to append all records in a file.
    Thanks in Advance.

    Hi,
    I think you have a while loop to hit the DB in your Process (As you said you have to fetch data from DB 10 times if 1000 rec are there)
    First sopy your DB O/P to one var
    and from second time append to previous data.(Otherwise you can directly use append from starting instead of copy and append)
    When loop completes you can transform to File adapter Var.
    Otherwise you can configure yourFileadapter such that it will aapend current records to previous records.
    You can use 'Append= true' in your file adapter wsdl.
    It will append previous records to current records in the same file.
    Regards
    PavanKumar.M

  • How to append paragraph in text file of TextEdit application using applescript

    how to append paragraph in text file of TextEdit application using applescript and how do i save as different location.

    christian erlinger wrote:
    When you want to print out an escape character in java (java is doing the work in client_text_io ), you'd need to escape it.
    client_text_io.put_line(out_file, replace('your_path', '\','\\'));cheersI tried replacing \ with double slash but it just printed double slash in the bat file. again the path was broken into two lines.
    file output
    chdir C:\\DOCUME~1\
    195969\\LOCALS~1\\Temp\
    Edited by: rivas on Mar 21, 2011 6:03 AM

  • 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

  • Importing from XML to Excel - need to know how to append to existing Excel file

    Hello,
    I have several XML files that I will need to import into one Excel spreadsheet. I have been able to figure out how to import an XML file to an Excel file but when I import a second XML file, the contents of the second XML overwrite the Excel spreadsheet.
    I am looking for an option to append. Thanks in advance
    private void XmlToExcel(string xmlFilePath, string excelFilePath)
    object misValue = System.Reflection.Missing.Value;
    DataSet Trans_ds = new System.Data.DataSet();
    Trans_ds.ReadXml(xmlFilePath);
    Excel.Application excel = new Excel.Application();
    excel.Application.Workbooks.Add(true);
    System.Data.DataTable table = Trans_ds.Tables[0];
    Worksheet worksheet = (Worksheet)excel.ActiveSheet;
    Range excelRange = (Excel.Range)worksheet.get_Range("A" + worksheet.Rows.Count, Type.Missing);
    int lastRow = excelRange.get_End(XlDirection.xlUp).Row;
    int ColumnIndex = 0;
    int rowIndex = lastRow++;
    foreach (System.Data.DataColumn col in table.Columns)
    ColumnIndex++;
    excel.Cells[lastRow, ColumnIndex] = col.ColumnName;
    foreach (DataRow row in table.Rows)
    rowIndex++;
    ColumnIndex = 0;
    foreach (DataColumn col in table.Columns)
    ColumnIndex++;
    excel.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName];
    worksheet.StandardWidth = 20.0;
    worksheet.SaveAs(excelFilePath, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
    excel.Quit();
    releaseObject(worksheet);
    releaseObject(excel);

    See if this helps.  I opened the old excel file and added the new rows into the existing workbook.
    private void XmlToExcel(string xmlFilePath, string excelFilePath, Boolean append)
    object misValue = System.Reflection.Missing.Value;
    DataSet Trans_ds = new System.Data.DataSet();
    Trans_ds.ReadXml(xmlFilePath);
    Excel.Application excel = new Excel.Application();
    Excel.Workbook Bk = excel.Workbooks.Add(true);
    System.Data.DataTable table = Trans_ds.Tables[0];
    Excel.Worksheet worksheet = (Excel.Worksheet)excel.Worksheets[1];
    Excel.Range excelRange = (Excel.Range)worksheet.get_Range("A" + worksheet.Rows.Count, Type.Missing);
    int lastRow = excelRange.get_End(Excel.XlDirection.xlUp).Row;
    int ColumnIndex = 0;
    int rowIndex = lastRow++;
    foreach (System.Data.DataColumn col in table.Columns)
    ColumnIndex++;
    excel.Cells[lastRow, ColumnIndex] = col.ColumnName;
    foreach (DataRow row in table.Rows)
    rowIndex++;
    ColumnIndex = 0;
    foreach (DataColumn col in table.Columns)
    ColumnIndex++;
    excel.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName];
    worksheet.StandardWidth = 20.0;
    if (append == false)
    worksheet.SaveAs(excelFilePath, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
    else
    //open old workbook
    Excel.Workbook oldworkbook = (Excel.Workbook)excel.Workbooks._Open(
    excelFilePath,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing);
    //get first sheet in workbook
    Excel.Worksheet oldxlSht = (Excel.Worksheet)oldworkbook.Worksheets[1];
    //get column A of old worksheet to find last row in sheet
    Excel.Range xlRange = (Excel.Range)oldxlSht.get_Range(
    "A" + oldxlSht.Rows.Count, Type.Missing);
    int LastRow = xlRange.get_End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;
    int newrow = LastRow + 1;
    //get last row of new worksheet
    xlRange = (Excel.Range)worksheet.get_Range(
    "A" + oldxlSht.Rows.Count, Type.Missing);
    LastRow = xlRange.get_End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;
    // copy rows of new worksheet to old worksheet
    xlRange = (Excel.Range)worksheet.Rows["1:" + LastRow, Type.Missing];
    xlRange.Copy(oldxlSht.Rows[newrow, Type.Missing]);
    oldworkbook.Save();
    excel.Quit();
    releaseObject(oldxlSht);
    releaseObject(worksheet);
    releaseObject(excel);
    jdweng

  • 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

  • How to append report to log file?

    Hai,
    how to append the sqlplusw sql query output to a file.
    If we use spool, every time the file will be overwritten with new content and it won't append.
    Note:
    In batch program using >> this we can write content in to a file.
    But in sqlplus how to append the query output to same file.

    hello egyptian god of the sun,
    you didn't mention that you were using 9i. if that is the case, one way i can think of... if you're using unix (which again i assume as you mention batch scripts '>>') is to save your sql script in a .sql file and execute it within a shell script but redirecting output to your log file. you can append as you normally would.

  • How to Append an existing Excel file?

    I am using the jexcel api to write to a new excel file. Each time i run my program, it creates a new Excel File by the name i give it. my code to create the excelFile is as below:-
    File excelFile=new File(workDir+"\\"+fileName+".xls");
    WritableWorkbook workbook = Workbook.createWorkbook(excelFile);
    After this code i write some data to a worksheet in the above mentioned excel file. But my requirement is that I want to create the excel if it does not exist, and if it exists, then the data should be appended to the worksheet in the existing excel file. At present it creates a new excel file and does not append it.
    How can it be done? does anyone have any suggestions as to how can i tackle this problem? please suggest something.
    Ankit

    There is no ready-to-run example, as you are searching for, available.
    This has several reasons:
    - It depends on the version of Excel. Examples for Excel 2007 might not work with Excel 2010 for instance.
    - No one just wants to open Excel without doing anything with it.
    The second point is something, i want to ask you:
    Why do you want to open an existing Excel file at all? What is it, what you want to do after opening it?
    If you have LV/C/C#/VB examples doing what you are looking for, why do you want to have it in TestStand directly, so NOT using existing code (saving time and effort) and basically re-inventing the wheel?
    ActiveX is an interface for remote controlling and embedding applications with/in other applications on Windows systems. It is a PROGRAMMING interface.
    So naturally, examples and tutorials exist for programming languages. Those examples are easily converted to TestStand sequences with a basic knowledge of the programming language and TestStand. Providing links for such tutorials/examples is a valid way to give support to fellow developers because we expect the fellow to have that basic knowledge. 
    If that knowledge is not present, i highly recommend to fill that gap.
    just my 2 cents,
    Norbert
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

  • How to append timestamp to log file in SQL*Plus ?

    Version: 11.2.0.3
    Platform : RHEL 5.8 (But I am looking for platform independant solution)
    I want to append the timestamp to spooled log file name in SQL*Plus.
    The spooled log filename should look like
    WMS_APP_23-March-2013.logI tried the following 3 methods found in the google. But none of them worked !
    I tried this
    col sysdt noprint new_value sysdt_var
    SELECT TO_CHAR(SYSDATE, 'yyyymmdd_hh24miss') sysdt FROM DUAL;
    spool run_filename_&sysdt_var.Logas suggested in
    http://power2build.wordpress.com/2011/03/11/sqlplus-spool-name-with-embedded-timestamp/
    and this
    spool filename with timestamp
    col sysdt noprint new_value sysdt
    SELECT TO_CHAR(SYSDATE, 'yyyymmdd_hh24miss') sysdt FROM DUAL;
    spool run_filename_&sysdt..Logas suggested in
    http://powerbuildev.wordpress.com/2011/03/11/sqlplus-spool-name-with-embedded-timestamp/
    and this
    column tm new_value file_time noprint
    select to_char(sysdate, 'YYYYMMDD') tm from dual ;
    prompt &file_time
    spool logfile_id&file_time..logas suggested in
    Creating a spool file with date/time appended to file name
    None of the above worked in RHEL or MS DOS. Any workaround ?

    I have tested your suggestions. But I still couldn't append the date to the logfile in RHEL or MS DOS SQL*Plus
    Here are the attempts I've made. I am posting how the logfile looked like after every test.
    #Attempt1 with two dots (&sysdate..log )
    set echo on
    set feedback on
    set define off
    set pages 999
    column dcol new_value SYSDATE noprint
    select to_char(sysdate,'YYYYMMDD') dcol from dual;
    spool testlog.&sysdate..log
    select 'hello' from dual;
    spool off;Log File Name -- > testlog.&sysdate..log
    #Attempt2 with single dot (&sysdate.log)
    set echo on
    set feedback on
    set define off
    set pages 999
    column dcol new_value SYSDATE noprint
    select to_char(sysdate,'YYYYMMDD') dcol from dual;
    spool testlog.&sysdate.log
    select 'hello' from dual;
    spool off;Log File Name ---> testlog.&sysdate.log
    #Attempt3. Replacing first dot with Hyphen (testlog- ) to check if the first dot was causing the issue
    set echo on
    set feedback on
    set define off
    set pages 999
    column dcol new_value SYSDATE noprint
    select to_char(sysdate,'YYYYMMDD') dcol from dual;
    spool testlog-&sysdate.log
    select 'hello' from dual;
    spool off;Log Filename: testlog-&sysdate.log
    #Attempt4: replacing SYSDATE with SDATE
    set echo on
    set feedback on
    set define off
    set pages 999
    column dcol new_value SDATE noprint
    select to_char(sysdate,'YYYYMMDD') dcol from dual;
    spool testlog1.&SDATE..log
    select 'hello' from dual;
    spool off;Log File Name -- > testlog1.&SDATE..log

  • Hi, may anyone tell me how to append text to a file's end?

    every time when i using FileOutputStream.write(byte[]) to add text to a file, the old content would be disappear. but my intention is append, not affect the old content. how to?
    thanx

    assuming it is a text file, read the text into a Reader, read the Reader's contents into a StringBuffer, close the Reader, append to the StringBuffer the new text and write it down to the file.
    regards

  • How to append data from one file to another

    Hello,
    I am trying to replace one column of numbers in a 2D array with a unique string from another file.
    Pos.    Serial    Gain
     2        3252        4
     4        15697      4
     6        15543      4
    I want to replace the "4" in the third column with a string obtained from another file, such as;
    Serial # 3252 Fuel Cell # arxe-2282
    Time and date 09:47   09/08/07
    Version 4.0
    Serial # 1234 Fuel Cell # arxf-0047
    Time and date 09:50   09/08/07
    Version 4.0
    In this case, I want to replace the "4" in the first row of the top file (after the header) with "arxe-2282" from the file just above.
    This means I need to search though the second file (which will have multiple entries) and find the same serial number (in this case "3252") and then write the "arxe-2282" string in place of the "4" in the top file, right next to the "3252" number there.
    The search part is proving difficult. I can replace the "4" easy enough, but only if I already know where the "arxe-2282" is in the second file.
    Any ideas?
    Tay

    try this.....
    the program uses the match pattern and scan from string functions.  And there is still room for improvement.
    If you have to do is more often with bigger files, you should create a lookup table first. currently the files is scanned each time ....
    Greetings from Germany
    Henrik
    LV since v3.1
    “ground” is a convenient fantasy
    '˙˙˙˙uıɐƃɐ lɐıp puɐ °06 ǝuoɥd ɹnoʎ uɹnʇ ǝsɐǝld 'ʎɹɐuıƃɐɯı sı pǝlɐıp ǝʌɐɥ noʎ ɹǝqɯnu ǝɥʇ'
    Attachments:
    find location.vi ‏11 KB

  • How to append to zip files

    I would like to know how to append to a zip file, I know how to write a zip file and I can put as many entries in the first time but if I run my program again and try to add a file to the same zip file it erases what was already in it. I use ZipOutputStream(new FileOutputStream), I have tried the FileOutputStream append but it does not seem to work for zip files, I have tried RandomAccessFile on my zip file but that just seems to add the bytes to the file that already in the zip file, and makes the file unopenable, corrupt. If you can help, please tell me how.

    You actually have to open the previous zipped file, read it's entries and their data and then rewrite a new zip file with these entries and their data. You can then delete your first file and rename the new one so the effect is that you have "appended" zip files to the existing archive.
    Here is an example which I pieced together from a larger bit of code that I have. This would need to be in a try/catch but this should give you a start.
    /** This method adds a new file to an existing zip file. It * includes all the zipped entries previously written.
    * @param file The old zip archive
    * @param filename The name of the file to be Added
    * @param data The data to go into the zipped file
    * NOTE: This method will write a new file and data to an archive, to
    * write an existing file, we must first read the data frm the file,
    * then you could call this method.
    public void addToArchive(File file, String filename, String data)
         ZipOutputStream zipOutput = null;
    ZipFile zipFile = null;
    Enumeration zippedFiles = null;
    ZipEntry currEntry = null;
    ZipEntry entry = null;
    zipFile = new ZipFile( file.getAbsolutePath() );
         //get an enumeration of all existing entries
    zippedFiles = zipFile.entries();
         //create your output zip file
    zipOutput = new ZipOutputStream( new FileOutputStream ( new File( "NEW" + file.getAbsolutePath() ) ) );
    //Get all the data out of the previously zipped files and write it to a new ZipEntry to go into a new file archive
    while (zippedFiles.hasMoreElements())
    //Retrieve entry of existing files
    currEntry = (ZipEntry)zippedFiles.nextElement();
    //Read data from existing file
    BufferedReader reader = new BufferedReader( new InputStreamReader( zipFile.getInputStream( currEntry ) ) );
    String currentLine = null;
    StringBuffer buffer = new StringBuffer();
    while( (currentLine = reader.readLine() ) != null )
    buffer.append( currentLine);
    //Commit the data
    zipOutput.putNextEntry(new ZipEntry(currEntry.getName()) ) ;
    zipOutput.write (buffer.toString().getBytes() );
    zipOutput.flush();
    zipOutput.closeEntry();
    //Close the old zip file
    zipFile.close();
    //Write the 'new' file to the archive, commit, and close
    entry = new ZipEntry( newFileEntryName );
    zipOutput.putNextEntry( entry );
    zipOutput.write( data.getBytes() );
    zipOutput.flush();
    zipOutput.closeEntry();
    zipOutput.close();
         //delete the old file and rename the new one
    File toBeDeleted = new File ( file.getAbsolutePath() );
    toBeDeleted.delete();
         File toBeRenamed = new File ( "NEW" + file.getAbsolutePath() );
    toBeRenamed.rename( file );
    Like I said I haven't tested this code as it is here but hopefully it can help. Good luck.

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

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

Maybe you are looking for

  • Upgrading from iPhone 3G to iPhone 4

    Two quick questions: 1. If the iPhone 4 has a micro sim slot, how did I get my phone numbers off my old sim onto my iPhone 4? 2. Is there any way to backup my application files? For example I am up to level 25 on F.A.S.T. and don't want to lose my ga

  • How can I convert Float numbers which are represented as 'E-05' to full precision

    I have over 6,000 records which all have 'E-05' in the field. It should actually be full precision, such as:  0.000046793055472781 How can I convert all of these?  There are around 600,000 records in the whole table, so I only want to convert the 'E-

  • Stack overflow exception when selecting the Organization tab on a contact card

    I have encountered a reproducible crash in the Lync 2013 client.  The crash happens after selecting the "Organization" tab when viewing a contact card. The crash appears to happen because of a stack overflow with MSO.DLL.  I have applied the latest h

  • OIM 11g upgrade and connector details

    Hi, We are planning to upgrade OIM 10g to OIM 11g. Please let me know the latest version of 1. OIM 11g 2. OID version for OIM 11g 3. HRMS version for OIM 11g 4. EBS version for OIM 11g 5. AD version for OIM 11g 6. Exchange version for OIM 11g Thanks

  • DAC to output to broadcast monitor

    Greetings! just scored a sony triniton monitor for $5! nice. so, now I am looking for an affordable Digital to Analog converter that will allow me to view the PPCS5 timeline on the monitor. any suggestions? budget would be around 300-400$