Next page | Contents page |

Object serialisation

For saving objects on disc and reading them back in - "persistence". Also used for sending objects "over a wire", eg for Remote Method Invocation (RMI). This is how you do it:

	MyClass obj = ...;  
	File f = new File (filePath);

	try
	{
		// To write an object:
		ObjectOutputStream sout = 
			new ObjectOutputStream (new FileOutputStream (f));
		sout.writeObject (obj);
		sout.close ();

		// To read an object back in:
		ObjectInputStream sin = 
			new ObjectInputStream (new FileInputStream (f));
		MyClass copy = (MyClass) sin.readObject ();
		sin.close ();
	}
	catch (IOException ex) { ... } 
	catch (ClassNotFoundException ex) { ... }
	catch (ClassCastException ex) { ... }

Notes

Next page | Contents page |