package Files; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; // examples of saving and reading objects from files public class SerializeFileExample { // read a serialized Bunny from an existing file public static Bunny readBunny() { Bunny bun = null; // files are teh dangers try { // stream that reads objects, buffered stream, file input stream ObjectInputStream stream = new ObjectInputStream( new BufferedInputStream( new FileInputStream(new File("bunny.txt")))); // temp to read into Object temp = ""; // what if the contents of the file are bad try { // get the current object from the file temp = stream.readObject(); // check that it was a valid Bunny if (temp != null && temp instanceof Bunny) { // if so, safe to cast bun = (Bunny) temp; } // ClassNotFound means there was an object but our project // doesn't have the code for that class } catch (ClassNotFoundException ex) { System.out.println("Bad File contents"); } // done with the file stream.close(); } catch (IOException ex) { System.out.println("could not access file"); } return bun; } // serialize a Bunny to a file public static void writeBunny() { // make bunny Bunny bun = new Bunny("Clyde", 4); try { // make a stream that can write serialized objects to file ObjectOutputStream stream = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(new File("bunny.txt")))); // put the bunny into the file stream.writeObject(bun); // since happy is transient, it will not be saved as part of the bunny // close the file stream.close(); } catch (IOException ex) { System.out.println("could not access file"); } } public static void main(String[] args) { writeBunny(); readBunny(); } }