Solved

saving my class types into file

Posted on 1998-11-23
3
171 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
  • 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB Script to add site to Java Exception List 4 49
servlet doXXX methods 3 35
windows explorer path to command prompt 5 29
how to add new optional parameter to JSP 1 27
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

911 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now