Package: java.io.* |
Product: JDK |
Release: 1.1.x |
Related Links: |
General
File
FilenameFilter
FileWriter
JPEGCodec
ObjectInputStream
OutputStream
PipedInputStream
PrintWriter
StreamTokenizer
|
Comment: |
ObjectOutputStream and ObjectInputStream can be used to write java.io.Serializable objects to a stream. The use of ObjectOutputStream to save a gameboard to a file.try { /* Scanning for saving file */ File game = new File( "terras.game" ); FileOutputStream ostream = new FileOutputStream( game ); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeObject( getBoardPanel().getBoardSize() ); // writing size of field for (int i=0; i < getBoardPanel().getBoardSize().width; i++) for (int j=0; j < getBoardPanel().getBoardSize().height; j++) { p.writeObject( getBoardPanel().getBoard()[i][j] ); } p.flush(); ostream.close(); } catch (Exception e) { System.out.println( e.getMessage() ); e.printStackTrace(); System.exit(0); }The use of ObjectInputStream to retrieve a saved gameboard.try { /* Scanning for saving file */ File game = new File( "terras.game" ); if ( ! game.exists() ) { throw new FileNotFoundException("cannot find previous 'terras.game' file"); } FileInputStream istream = new FileInputStream( game ); ObjectInputStream p = new ObjectInputStream(istream); Dimension sze = (Dimension) p.readObject( ); //getBoardPanel().getSize() Component [][] board = new Component[sze.width][sze.height]; // writing size of field for (int i=0; i < sze.width; i++) for (int j=0; j < sze.height; j++) { board[i][j] = (Component) p.readObject(); } getBoardPanel().setBoard( board ); validate(); istream.close(); } catch (FileNotFoundException e) { System.out.println( e.getMessage() ); } catch (Exception e) { System.out.println( e.getMessage() ); e.printStackTrace(); System.exit(0); } |