//ObjectFile.java //File of objects. can be mix of different classes and primitives too. import java.io.*; import javax.swing.*; public class ObjectFile { public static void main( String[] args ) { X x1 = new X(); X x2 = new X(5,2.3,"hello"); X[] xArray = new X[100]; System.out.println("x1= " + x1 ); System.out.println("x2= " + x2 ); File outFile; FileOutputStream outFileStream; ObjectOutputStream outObjectStream; try { outFile = new File( "sampleObjects.data" ); outFileStream = new FileOutputStream( outFile ); outObjectStream = new ObjectOutputStream( outFileStream ); outObjectStream.writeObject( x1 ); outObjectStream.writeObject( x2 ); // array (or Collection) of objects can be dumped to file: //optionally preceded by int number of objects that follow //outObjectStream.writeInt( xArray.length ); //outObjectStream.writeObject( xArray ); outObjectStream.close(); } catch (IOException e) { System.out.println( "threw an IOException...deal with it..." ); } File inFile; FileInputStream inFileStream; ObjectInputStream inObjectStream; try { inFile = new File( "sampleObjects.data" ); inFileStream = new FileInputStream( inFile ); inObjectStream = new ObjectInputStream( inFileStream ); x2 = (X) inObjectStream.readObject(); //swap x1 and x2 x1 = (X) inObjectStream.readObject(); //readObject returns Object //contents of file can be read into array of objects //optionally preceded by reading size of array //int size = inObjectStream.readInt(); //System.out.println("size= " + size ); //xArray = (X[]) inObjectStream.readObject(); inObjectStream.close(); } catch (IOException e) { System.out.println( "threw an IOException...deal with it..." ); } catch (ClassNotFoundException e) { //readObject can throw this System.out.println( "threw an ClassNotFoundException...deal with it..." ); } //demo purposes to show input from file has happened System.out.println("x1= " + x1 ); System.out.println("x2= " + x2 ); } } //class that can read/written from/to file must implement Serializable //interface that has no methods (i.e. a "marker" interface) class X implements Serializable { int iX; double dX; String sX; public X() { iX = 0; dX = 0; sX = "zilch"; } public X( int i, double d, String s ) { iX = i; dX = d; sX = new String( s ); } public String toString() { return "[ " + iX + " " + dX + " " + sX + " ]"; } }