Fhernd

BlackBox.java

Mar 5th, 2026
14,865
0
Never
7
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. public class BlackBox implements Serializable {
  2.  
  3.     private long altitude;
  4.     private double speed;
  5.     private float engineTemperature;
  6.     private static final long serialVersionUID = 1L;
  7.  
  8.     public BlackBox(long altitude, double speed, float engineTemperature) {
  9.         this.altitude = altitude;
  10.         this.speed = speed;
  11.         this.engineTemperature = engineTemperature;
  12.     }
  13.  
  14.     // Saving the state of the object as a byte stream
  15.     public byte[] getState() throws IOException {
  16.         ByteArrayOutputStream bos = new ByteArrayOutputStream();
  17.         ObjectOutput out = null;
  18.         byte[] memento = null;
  19.         try {
  20.             out = new ObjectOutputStream(bos);
  21.             out.writeObject(this);
  22.             out.flush();
  23.             memento = bos.toByteArray();
  24.         } finally {
  25.             try {
  26.                 bos.close();
  27.             } catch (IOException ex) {
  28.                 // ignore close exception
  29.             }
  30.         }
  31.         return memento;
  32.     }
  33.  
  34.     // Restoring state from memento
  35.     public BlackBox setState(byte[] memento) throws Exception {
  36.         ByteInputStream bis = new ByteInputStream(memento, memento.length);
  37.  
  38.         ObjectInputStream objectInputStream
  39.                 = new ObjectInputStream(bis);
  40.         BlackBox blackBox = (BlackBox) objectInputStream.readObject();
  41.         objectInputStream.close();
  42.         return blackBox;
  43.     }
  44.  
  45. }
Advertisement