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
Solved

saving my class types into file

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
session migration servlets 2 42
Java exception bubble up 2 21
difference between sorce folder and folder in eclipise 3 28
collection output issue 9 36
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
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 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…
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:

840 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