Solved

saving my class types into file

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
how to use external config file with Spring MVC 4 61
countX 22 70
Groovy:unable to resolve class error 2 31
Java Loop 4 3
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…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

705 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

18 Experts available now in Live!

Get 1:1 Help Now