Solved

saving my class types into file

Posted on 1998-11-23
3
178 Views
Last Modified: 2010-03-30
i have read that with the class: java.io.ObjectOutputStream, i can write to and from a file without the need to implement the writing and reading functions , but only with the: .readObject and .writeObject.
if i created my own class, can i use these methods (and how)?
0
Comment
Question by:rzvika2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
3 Comments
 
LVL 5

Accepted Solution

by:
fontaine earned 100 total points
ID: 1228033
The is called object serialization. This technique allows you to turn the state of an object
into a stream of bytes (that you can store in a file on disk, send through a network, etc.),
and later recover the original object (with its original state of course). The condition
on the class you want to serialize is that it implements java.io.Serializable. Also, if you
are referring to other objects, they also have to implement Serializable (otherwise, the
serialization will fail and you will have a java.io.NotSerializableException). Some classes
of the JDK already implement Serializable. This is the case, for example, of Vector and
Hashtable.

Sample code:

public class IntegerStore implements java.io.Serializable {

    private int integer = 0;

    public class IntegerStore() {
    }

    public int getInteger() {
       return integer;
    }

    public void setInteger(int integer) {
        this.integer = integer;
        return;
    }

    public static void main(String args[])  throws Exception {
        IntegerStore  store = new IntegerStore ();
        store.setInteger(5);

        // serialization + storing in "integerstore.ser"
        FileOutputStream out = new FileOutputStream("integerstore.ser");
        BufferedOutputStream bufOut = new BufferedOutputStream(out);
        ObjectOutputStream objOut = new ObjectOutputStream(bufOut);
        objOut.writeObject(store);
        objOut.close();        

        // now, we recover the serialized object!
        FileInputStream in = new FileInputStream("integerstore.ser");
        BufferedInputStream bufIn = new BufferedInputStream(in);
        ObjectInputStream objIn = new ObjectInputStream(bufIn);
        IntegerStore recoveredStore = (IntegerStore )objIn.readObject();
        objIn.close();

        System.out.println("The value was " + recoveredStore.getInteger() + "!");
        return;
    }
}
0
 
LVL 5

Expert Comment

by:fontaine
ID: 1228034
Note: you will have to import java.io.* to compile the code above. Here is an article that
should interest you:

http://www.javaworld.com/javaworld/jw-05-1997/jw-05-persistence.html
0
 
LVL 5

Expert Comment

by:fontaine
ID: 1228035
I see that there is a typing error in the code. I repost it entirely for clarity.
An IntegerSore object is built (called "store" in the example). It holds an
integer value that we set to 5. We then serialize it and store it in the
"integerstore.ser" file. Finally, we read back this file, and recover its
content as an IntegerStore. We print out the value it holds to be sure
that we do not deal with an IntegerStore created "from scratch" (as
we would have if we were building the "recoveredStore" instance
using "new IntegerStore()"). As we read "5", and not "0", we have
proven that the state of the object was saved in the file and that we
were able to recover it.

import java.io.*;

   public class IntegerStore implements java.io.Serializable {

       private int integer = 0;

       public IntegerStore() {
       }

       public int getInteger() {
          return integer;
       }

       public void setInteger(int integer) {
           this.integer = integer;
           return;
       }

       public static void main(String args[])  throws Exception {
           IntegerStore  store = new IntegerStore ();
           store.setInteger(5);

           // serialization + storing in "integerstore.ser"
           FileOutputStream out = new FileOutputStream("integerstore.ser");
           BufferedOutputStream bufOut = new BufferedOutputStream(out);
           ObjectOutputStream objOut = new ObjectOutputStream(bufOut);
           objOut.writeObject(store);
           objOut.close();        

           // now, we recover the serialized object!
           FileInputStream in = new FileInputStream("integerstore.ser");
           BufferedInputStream bufIn = new BufferedInputStream(in);
           ObjectInputStream objIn = new ObjectInputStream(bufIn);
           IntegerStore recoveredStore = (IntegerStore )objIn.readObject();
           objIn.close();

           System.out.println("The value was " + recoveredStore.getInteger() + "!");
           return;
       }
   }
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
xampp tool 12 58
Opening PDF on button click and fill new document 2 54
Why my table column Id is not passed to java object? 4 46
dao vs facade design patterns 2 34
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question