In this example, simple String and Integer variables are written to a file and then read from that file. It illustrates the use of the ObjectOutputStream and ObjectInputStream classes.
The program is written as an application and must be run manually.
import java.io.*; public class jbsBasic implements Serializable { public static void main ( String arg[] ) { String host = "jbspc.cs.unc.edu"; Integer port = new Integer ( 8080 ); try { FileOutputStream fos = new FileOutputStream ( "testFile.dat" ); ObjectOutputStream oos = new ObjectOutputStream ( fos ); System.out.println ( "Write:" ); System.out.println ( " Host=" + host ); System.out.println ( " Port=" + port.toString() ); oos.writeObject ( host ); oos.writeObject ( port ); oos.flush (); oos.close (); } catch ( Exception e ) { System.out.println ( "Error in ObjectOutput" ); } try { FileInputStream fis = new FileInputStream ( "testFile.dat" ); ObjectInputStream ois = new ObjectInputStream ( fis ); String inHost = (String)ois.readObject (); Integer inPort = (Integer)ois.readObject (); ois.close (); System.out.println (); System.out.println ( "Read:" ); System.out.println ( " Host=" + inHost ); System.out.println ( " Port=" + inPort.toString() ); } catch ( Exception e ) { System.out.println ( "Error in ObjectOutput" ); } } // end main } // end jbsBasic