Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9219293
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T03:04:58+00:00 2026-06-18T03:04:58+00:00

I am trying to understand object serialization better, so I am practicing with some

  • 0

I am trying to understand object serialization better, so I am practicing with some code I got from my textbook. (My textbook doesn’t explain how to read and write/append objects to a serialization file every time the program starts, which is what I need to do.) I took their program, which just overwrites existing data in a file with the objects from the current session, and add code to it so that it will append the objects and read the whole file instead. I found something really useful here: Appending to an ObjectOutputStream but even if I create a subclass of ObjectOutputStream, override the writeStreamHeader method, and call this subclass if the file already exists, which is what they did, it still throws a CorruptedStreamException. My guess is that I would need to set the pointer back to the beginning of the file, but that doesn’t seem to be necessary as there is only one ObjectOutputStream. So, my question is, what else could I possibly need to do?

EDIT: Here is some code.

WriteData.java

import java.io.*;
import java.util.Scanner;

public class WriteData 
{
    private int number;
    private String name; 
    private float money;
    private ObjectInputStream testopen;
    private ObjectOutputStream output;  //This is for the output. Make sure that
    //this object gets an instance of FileOutputStream so that it can write objects
    //to a FILE.
    private AppendObjectOutputStream appendobjects;
    static Scanner input = new Scanner(System.in);
    static DataClass d;

    public void openfile()
    {
        //Try opening a file (it must have the ".ser" extension).
        try
        {
            //output = new ObjectOutputStream(new FileOutputStream("test.ser"));
            testopen = new ObjectInputStream(new FileInputStream("test.ser"));
        }
        //If there is a failure, throw the necessary error.
        catch (IOException exception)
        {
            try 
            {
                output = new ObjectOutputStream(new FileOutputStream("test.ser"));
            } 
            catch (FileNotFoundException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }   //end case createfile
        if (testopen != null)
        {
            try 
            {
                testopen.close();
                appendobjects = new AppendObjectOutputStream(
                        new FileOutputStream("test.ser"));
            } 
            catch (FileNotFoundException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public void writedata()
    {
        //write the data until the user enters a sentry value.
        System.out.println("Enter CTRL + z to stop input.\n");
        System.out.print ("Enter the data in the following format: " +
                "account_number name balance\n->");
        while (input.hasNext())
        {
            System.out.print ("Enter the data in the following format: " +
                        "account_number name balance\n->");
            try
            {
                number = input.nextInt();
                name = input.next();
                money = input.nextFloat();

                //Make object with that data
                d = new DataClass(number, name, money);
                //write it to the file
                if (output != null)
                {
                    output.writeObject(d);
                }
                else if (appendobjects != null)
                {
                    appendobjects.writeObject(d);
                }
            }
            catch (IOException e)
            {
                System.out.println("Error writing to file.");
                return;
            }
        }
        System.out.println("\n");
    }   //end writedata
    public void closefile()
    {
        try 
        {
            if (output != null)
            {
                output.close();
            }
            else if (appendobjects != null)
            {
                appendobjects.close();
            }
        }
        catch (IOException e)
        {
            System.out.println("Error closing file. Take precautions");
            System.exit(1);
        }
    }
}

DataClass.java

import java.io.Serializable;

public class DataClass implements Serializable
{
    private int someint;
    private String somestring;
    private float somefloat;
    public DataClass(int number, String name, float amount) 
    {
        setint(number);
        setstring(name);
        setfloat(amount);
    }
    public void setint(int i)
    {
        this.someint = i;
    }
    public int getint()
    {
        return someint;
    }
    public void setstring(String s)
    {
        this.somestring = s;
    }
    public String getstring()
    {
        return somestring;
    }
    public void setfloat(float d)
    {
        this.somefloat = d;
    }
    public float getfloat()
    {
        return somefloat;
    }
}

AppendObjectOutputStream.java

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;


public class AppendObjectOutputStream extends ObjectOutputStream 
{
    public AppendObjectOutputStream(FileOutputStream arg0) throws IOException 
    {
        super(arg0);
        // TODO Auto-generated constructor stub
    }
    //This is a function that is default in ObjectOutputStream. It just writes the 
    //header to the file, by default. Here, we are just going to reset the 
    //ObjectOutputStream
    @Override
    public void writeStreamHeader() throws IOException
    {
        reset();
    }

}

ReadData.java

import java.io.*;
import java.util.Scanner;

public class ReadData 
{ 
    private FileInputStream f;
    private ObjectInputStream input;    //We should the constructor for this 
    //object an object of FileInputStream
    private Scanner lines;
    public void openfile()
    {
        try
        {
            f = new FileInputStream("test.ser");
            input = new ObjectInputStream (f);
            //input.reset();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.exit(1);
        }
    }
    public void readdata()
    {
        DataClass d;
        System.out.printf("%-15s%-12s%10s\n", "Account Number", "First Name",
                "Balance");
        try
        {
            while (true)
            {
                d = (DataClass)input.readObject();  //define d
                //read data in from d
                System.out.printf("%-15d%-12s%10.2f\n", d.getint(), d.getstring(),
                        d.getfloat());
            }
        }
        catch (EOFException eof)
        {
            return;
        } 
        catch (ClassNotFoundException e) 
        {
            System.err.println("Unable to create object");
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }

    }
    public void closefile()
    {
        try
        {
            if (input != null)
            {
                input.close();
            }
        }
        catch (IOException ex)
        {
            System.err.println("Error closing file.");
            System.exit(1);
        }
    }
}

SerializationTest.java

public class SerializationTest 
{

    public static void main(String[] args)
    {
        ReadData r = new ReadData();
        WriteData w = new WriteData();
        w.openfile();
        w.writedata();
        w.closefile();
        r.openfile();
        r.readdata();
        r.closefile();

    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T03:04:58+00:00Added an answer on June 18, 2026 at 3:04 am

    I suggest to do it this way

        ObjectOutputStream o1 = new ObjectOutputStream(new FileOutputStream("1"));
        ... write objects
        o1.close();
        ObjectOutputStream o2 = new AppendingObjectOutputStream(new FileOutputStream("1", true));
        ... append objects
        o2.close();
    

    it definitely works.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to understand JQ better. I'm calling an JQ object $(.FamiliesList li li
I was trying to understand what object decomposition means and read a lot of
HI Trying to understand how __radd__ works. I have the code >>> class X(object):
All I'm trying to understand the obejctive C object runtime process From the Object
I'm trying to understand what's going on in the following code. When object-a is
Here's the code I'm trying to understand (it's from http://apocalisp.wordpress.com/2010/10/17/scalaz-tutorial-enumeration-based-io-with-iteratees/ ): object io {
I am trying to understand what the object.GetHashCode() is used for. I read that
I'm trying to understand when I should call Query.close(Object) or Query.closeAll(); From the docs
Trying to understand the results I am getting from object equality ... Ok first
Im trying to send some object from a server to the client. My problem

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.