Ejemplo n.º 1
0
  public static void main(String[] args) throws IOException, ClassNotFoundException {

    Singleton instance = Singleton.getInstance();

    // Serializing the singleton instance
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton.tmp"));
    oos.writeObject(instance);
    oos.close();

    // Recreating the instance by reading the serialized object data store
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("singleton.tmp"));
    Singleton singleton = (Singleton) ois.readObject();
    ois.close();

    // Recreating the instance AGAIN by reading the serialized object data store
    ObjectInputStream ois2 = new ObjectInputStream(new FileInputStream("singleton.tmp"));
    Singleton singleton1 = (Singleton) ois2.readObject();
    ois2.close();

    // The singleton behavior have been broken
    System.out.println("Instance reference check : " + singleton.getInstance());
    System.out.println("Instance reference check : " + singleton1.getInstance());
    System.out.println("=========================================================");
    System.out.println("Object reference check : " + singleton);
    System.out.println("Object reference check : " + singleton1);
  }
Ejemplo n.º 2
0
 // returns a deep copy of an object
 public static Object deepCopy(Object oldObj) {
   ObjectOutputStream oos = null;
   ObjectInputStream ois = null;
   try {
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
     oos = new ObjectOutputStream(bos); // B
     // serialize and pass the object
     oos.writeObject(oldObj); // C
     oos.flush(); // D
     ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); // E
     ois = new ObjectInputStream(bin); // F
     // return the new object
     Object object = ois.readObject();
     oos.close();
     ois.close();
     return object; // G
   } catch (Exception e) {
     return null;
   } finally {
     try {
       if (oos != null) oos.close();
       if (ois != null) ois.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Ejemplo n.º 3
0
 /** @see util.ObjStream#toArray() */
 public final Object[] toArray() throws IOException {
   if (in == null) return null;
   ObjectInputStream instr = new ObjectInputStream(new FileInputStream(file));
   Vector res = new Vector();
   Object[] resArray = null;
   Object tw = null;
   try {
     try {
       while (true) {
         tw = instr.readObject();
         res.add(tw);
       }
     } catch (EOFException e) {
     }
     resArray = new Object[res.size()];
     res.toArray(resArray);
   } catch (ClassNotFoundException e) {
   }
   in.close();
   instr.close();
   instr = null;
   in = null;
   file.delete();
   return resArray;
 }
Ejemplo n.º 4
0
 // TODO Der kommer en EOF exception når der forsøges at readObject.
 // TODO Brug sharedpref til at gemme og læse tamagotchi.
 private synchronized void loadTamagotchiFromFile() {
   FileInputStream fis = null;
   try {
     available.acquire();
     Log.d(TAMAGOTCHI, "Loading the tamagotchi from: " + fileName);
     fis = this.openFileInput(fileName);
     ObjectInputStream is = new ObjectInputStream(fis);
     // is.reset();
     // TODO Bug when reading a tama from filesystem
     // Steps to reproduce: Kill with the app context menu thingie, start app again.
     tama = (Tamagotchi) is.readObject();
     if (tama == null) return;
     is.close();
     fis.close();
     initializePlayingfield();
     Log.d(TAMAGOTCHI, "Done loading the tama");
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     e.printStackTrace();
   } catch (OptionalDataException e) {
     e.printStackTrace();
   } catch (StreamCorruptedException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (InterruptedException e) {
     e.printStackTrace();
   } finally {
     available.release();
   }
 }
Ejemplo n.º 5
0
 /**
  * A getter for the high scores list. Reads it directly from file and throws an error if the file
  * is not found (!working on this!).
  *
  * @return Object[][] where [i][0] is the rank (String), [i][1] is the name (String) and [i][2] is
  *     the score (Integer).
  */
 public static Object[][] getHighScore() {
   if (!new File("HighScores.dat").exists()) {
     // This object matrix actually stores the information of the high scores list
     Object[][] highScores = new Object[10][3];
     // We fill the high scores list with blank entries:  #.    " "    0
     for (int i = 0; i < highScores.length; i++) {
       highScores[i][0] = (i + 1) + ".";
       highScores[i][1] = " ";
       highScores[i][2] = 0;
     }
     // This actually writes and makes the high scores file
     try {
       ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
       o.writeObject(highScores);
       o.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   try {
     // Read and return the read object matrix
     ObjectInputStream o = new ObjectInputStream(new FileInputStream("HighScores.dat"));
     Object[][] highScores = (Object[][]) o.readObject();
     o.close();
     return highScores;
   } catch (IOException | ClassNotFoundException e) {
     e.printStackTrace();
   }
   return null;
 }
Ejemplo n.º 6
0
  public static void main(String args[]) {
    ObjectInputStream in = null;
    try {
      in = new ObjectInputStream(new FileInputStream("output7.dat"));

      while (true) {
        Rectangle obj = (Rectangle) in.readObject();
        System.out.println("넓이 : " + obj.width);
        System.out.println("높이 : " + obj.height);
      }

    } catch (FileNotFoundException fnfe) {
      System.out.println("파일이 존재하지 않습니다.");

    } catch (EOFException eofe) { // 파일로부터 더이상 읽을 객체가 없을때 발생하는 예외처리를 합니다.
      System.out.println("시마이.");

    } catch (IOException ioe) {
      System.out.println(ioe.getMessage());

    } catch (ClassNotFoundException cnfe) {
      System.out.println("해당 클래스가 존재하지 않습니다.");

    } finally {
      try {
        in.close(); // 파일 종료

      } catch (Exception e) { // close메소드가 발생하는 예외처리
      }
    }
  }
Ejemplo n.º 7
0
  /**
   * Clone a <code>Serializable</code> object; for use when a <code>clone()</code> method is not
   * available.
   *
   * @param obj object to clone
   * @return clone object
   * @throws RuntimeException
   */
  public static Object cloneSerializable(Object obj) {
    Object ret = null;

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream(StreamUtils.DEFAULT_BUFFER_SIZE);
      ObjectOutputStream oos = new ObjectOutputStream(baos);
      oos.writeObject(obj);
      oos.close();

      ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
      ObjectInputStream ois = new ObjectInputStream(bis);

      try {
        ret = ois.readObject();
      } catch (ClassNotFoundException cnfe) {
        assert false;
      }

      ois.close();
    } catch (IOException ioex) {
      throw new RuntimeException("Unable to clone object: " + obj);
    }

    return ret;
  }
Ejemplo n.º 8
0
  /*
   * receive process sent from slaves via socket
   */
  public void receiveProcess() throws IOException, ClassNotFoundException {
    ServerSocket listener = null;
    Socket socket;
    ObjectInputStream in = null;

    try {
      // 1. creating a server socket
      listener = new ServerSocket(getPort());

      while (true) {

        // 2. wait for connection
        System.out.println("Master Waiting for Slave");
        socket = listener.accept();
        System.out.println("Connection received from " + listener.getInetAddress().getHostName());

        // 3.read object from inputstream
        in = new ObjectInputStream(socket.getInputStream());
        //				String s = (String) in.readObject();
        //				System.out.println("Message Received from slave" + s);

        MigratableProcess process = (MigratableProcess) in.readObject();
        processList.add(process);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 4.close connection
      in.close();
      listener.close();
    }
  }
Ejemplo n.º 9
0
  public static GA GAWithCheckpoint(String checkpoint) throws Exception {
    File checkpointFile = new File(checkpoint);
    FileInputStream zin = new FileInputStream(checkpointFile);
    GZIPInputStream in = new GZIPInputStream(zin);
    ObjectInputStream oin = new ObjectInputStream(in);

    Checkpoint ckpt = (Checkpoint) oin.readObject();
    GA ga = ckpt.ga;
    ga._checkpoint = ckpt;
    ckpt.checkpointNumber++; // because it gets increased only after ckpt is
    // written

    oin.close();

    System.out.println(ckpt.report.toString());

    // Do we want to append to the file if it exists? Or just overwrite it?
    // Heu! Quae enim quaestio animas virorum vero pertemptit.
    // Wowzers! This is, indeed, a question that truly tests mens' souls.

    if (ga._outputfile != null) ga._outputStream = new FileOutputStream(new File(ga._outputfile));
    else ga._outputStream = System.out;

    return ga;
  }
Ejemplo n.º 10
0
  public static void Ex() {
    System.out.println("-- do zapisu --");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    DowodOsobisty z = new DowodOsobisty(br);
    z.info();

    try {
      ObjectOutputStream outp = new ObjectOutputStream(new FileOutputStream("plik.dat"));
      outp.writeObject(z);
      outp.close();
    } catch (Exception e) {
      System.out.println(e);
    }

    System.out.println("\n-- z pliku --");
    ObjectInputStream inp;

    try {
      inp = new ObjectInputStream(new FileInputStream("plik.dat"));
      Object o = inp.readObject();
      DowodOsobisty x = (DowodOsobisty) o;
      inp.close();
      x.info();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  /** Method: addToFile(LinkedList<GameNode> g) */
  @Test
  public void testAddToFile() throws Exception {
    GameNode testGameNode = new GameNode();
    testGameNode.setPlayer("rarry");
    testGameNode.setOpponent("lobertie");
    testGameNode.setGameName("raddle");
    testGameNode.setWinLose(true);
    testGameNode.setScore(29);
    LinkedList<GameNode> testLLGN = new LinkedList<GameNode>();
    testLLGN.add(testGameNode);
    testScoreboard.addToFile(testLLGN);

    LinkedList<GameNode> temp = new LinkedList<GameNode>();
    ObjectInputStream i = null;
    try {
      i = new ObjectInputStream(new FileInputStream("gameStats.ser"));
      temp = (LinkedList<GameNode>) i.readObject();
      i.close();
    } catch (FileNotFoundException e) {

    } catch (IOException e) {

    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    assertTrue(
        "The Object read from file contains the testGameNode added to file",
        temp.contains(testGameNode));
  }
  public List<Supplier> GetSuppliers() {
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    List<Supplier> suppliers = new ArrayList<Supplier>();

    try {
      fis = new FileInputStream("Suppliers.dat");
      ois = new ObjectInputStream(fis);

      while (true) {
        try {
          suppliers.add((Supplier) ois.readObject());
        } catch (EOFException ex) {
          break;
        }
      }
    } catch (IOException ex) {
      System.out.println("Falha ao Ler arquivo de fornecedores!");
      ex.getStackTrace();
    } catch (ClassNotFoundException e) {
      System.out.println("Falha ao Ler arquivo de fornecedores!");
      e.printStackTrace();
    } finally {
      try {
        if (ois != null) ois.close();
        if (fis != null) fis.close();
      } catch (IOException ex) {
        System.out.println("Falha ao Ler arquivo de fornecedores!");
        ex.getStackTrace();
      }
    }

    return suppliers;
  }
Ejemplo n.º 13
0
  /** DOCUMENT ME! */
  public void loadRaids() {
    File f = new File(REPO);

    if (!f.exists()) {
      return;
    }

    FileInputStream fIn = null;
    ObjectInputStream oIn = null;

    try {
      fIn = new FileInputStream(REPO);
      oIn = new ObjectInputStream(fIn);
      // de-serializing object
      raids = (HashMap<String, GregorianCalendar>) oIn.readObject();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      try {
        oIn.close();
        fIn.close();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
 /** Stop talking to the server */
 public void stop() {
   if (socket != null) {
     // Close all the streams and socket
     if (out != null) {
       try {
         out.close();
       } catch (IOException ioe) {
       }
       out = null;
     }
     if (in != null) {
       try {
         in.close();
       } catch (IOException ioe) {
       }
       in = null;
     }
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException ioe) {
       }
       socket = null;
     }
   } else {
     // Already stopped
   }
   // Make sure the right buttons are enabled
   start_button.setEnabled(true);
   stop_button.setEnabled(false);
   setStatus(STATUS_STOPPED);
 }
  public ServerSolution() {
    accountMap = new HashMap<String, Account>();
    File file = new File(fileName);
    ObjectInputStream in = null;
    try {
      if (file.exists()) {
        System.out.println("Reading from file " + fileName + "...");
        in = new ObjectInputStream(new FileInputStream(file));

        Integer sizeI = (Integer) in.readObject();
        int size = sizeI.intValue();
        for (int i = 0; i < size; i++) {
          Account acc = (Account) in.readObject();
          if (acc != null) accountMap.put(acc.getName(), acc);
        }
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 16
0
 @SuppressWarnings({"boxing", "unchecked"})
 public void loadCache() {
   this.cache.clear();
   try {
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(CACHE_FILE));
     this.remoteDiscoveryImpl.syso("load cache");
     try {
       final int cacheSize = (Integer) in.readObject();
       //					syso("size "+cacheSize);
       for (int i = 0; i < cacheSize; ++i) {
         HashMap<RemoteManagerEndpoint, Entry> rmee = new HashMap<RemoteManagerEndpoint, Entry>();
         Class<? extends Plugin> plugin = (Class<? extends Plugin>) in.readObject();
         this.remoteDiscoveryImpl.syso(plugin.getCanonicalName());
         //						syso("\t"+i+"'"+pluginName+"'");
         int numEntries = (Integer) in.readObject();
         //						syso("\t"+numEntries);
         for (int j = 0; j < numEntries; ++j) {
           Entry entry = (Entry) in.readObject();
           //							syso("\t\t"+entry);
           rmee.put(entry.manager, entry);
         }
         this.cache.put(plugin, rmee);
       }
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
     } finally {
       in.close();
     }
   } catch (FileNotFoundException e) {
     this.remoteDiscoveryImpl.logger.warning("Loading cache file" + CACHE_FILE + " failed.");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 17
0
  public void run() {
    try {
      System.out.println("socked");
      sock = new Socket(ii, pp);
      oout = new ObjectOutputStream(sock.getOutputStream());
      oout.flush();

      oin = new ObjectInputStream(sock.getInputStream());
      System.out.println("read ");
      rf.setLength(0);
      do {
        System.out.println("read ");
        file f = (file) oin.readObject();
        if (f.length <= 0) break;
        write(f);
      } while (true);
      oout.close();
      oin.close();
      rf.close();
      sock.close();
      xx.ConfirmPopup("Haua file namano shesh!!!");

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 18
0
 public static Object loadObjectFromFile(String fileName) throws Exception {
   FileInputStream fis = new FileInputStream(fileName);
   ObjectInputStream ois = new ObjectInputStream(fis);
   Object obj = ois.readObject();
   ois.close();
   return obj;
 }
Ejemplo n.º 19
0
 public CompiledScriptCache loadCompiledScriptCache() {
   if (Config.SCRIPT_CACHE) {
     File file = new File(SCRIPT_FOLDER, "CompiledScripts.cache");
     if (file.isFile()) {
       ObjectInputStream ois = null;
       try {
         ois = new ObjectInputStream(new FileInputStream(file));
         CompiledScriptCache cache = (CompiledScriptCache) ois.readObject();
         return cache;
       } catch (InvalidClassException e) {
         _log.fatal(
             "Failed loading Compiled Scripts Cache, invalid class (Possibly outdated).", e);
       } catch (IOException e) {
         _log.fatal("Failed loading Compiled Scripts Cache from file.", e);
       } catch (ClassNotFoundException e) {
         _log.fatal("Failed loading Compiled Scripts Cache, class not found.", e);
       } finally {
         try {
           ois.close();
         } catch (Exception e) {
         }
       }
       return new CompiledScriptCache();
     } else return new CompiledScriptCache();
   }
   return null;
 }
Ejemplo n.º 20
0
  public ArrayList<FIncomePO> findbyHall(String hall) throws RemoteException, IOException {
    ArrayList<FIncomePO> income = new ArrayList<FIncomePO>();
    ObjectInputStream os = null;
    System.out.println("start find!");
    try {
      FileInputStream fs = new FileInputStream(file);
      os = new ObjectInputStream(fs);
      FIncomePO po = (FIncomePO) os.readObject();

      while (fs.available() > 0) {
        byte[] buf = new byte[4];
        fs.read(buf);
        FIncomePO incomepo = (FIncomePO) os.readObject();

        if (incomepo.getShop().equals(hall)) {
          income.add(incomepo);
        }
      }

      return income;
    } catch (Exception e) {
      return null;
    } finally {
      os.close();
    }
  }
Ejemplo n.º 21
0
  public void checkSlave() throws IOException, ClassNotFoundException {
    ServerSocket listener = null;
    Socket socket;
    ObjectInputStream in = null;

    try {
      // 1. creating a server socket
      listener = new ServerSocket(15440);

      while (true) {

        // 2. wait for connection
        //				System.out.println("Waiting for checkSlave");
        socket = listener.accept();

        // 3.read object from inputstream
        in = new ObjectInputStream(socket.getInputStream());
        SlaveBean slave = (SlaveBean) in.readObject();
        slaveList.put(slave, slave.getCurCount());
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // 4.close connection
      in.close();
      listener.close();
    }
  }
Ejemplo n.º 22
0
  public ArrayList<FIncomePO> findByTime(String time1, String time2)
      throws RemoteException, IOException {
    ArrayList<FIncomePO> income = new ArrayList<FIncomePO>();
    ObjectInputStream os = null;

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    try {
      Date date1 = formatter.parse(time1);
      Date date2 = formatter.parse(time2);

      FileInputStream fs = new FileInputStream(file);
      os = new ObjectInputStream(fs);
      FIncomePO po = (FIncomePO) os.readObject();

      while (fs.available() > 0) {
        byte[] buf = new byte[4];
        fs.read(buf);
        FIncomePO incomepo = (FIncomePO) os.readObject();

        if (formatter.parse(incomepo.getTime()).after(date1)
            && formatter.parse(incomepo.getTime()).before(date2)) {

          income.add(incomepo);
        }
      }

      return income;
    } catch (Exception e) {
      return null;
    } finally {
      os.close();
    }
  }
  /** Loads the extraction model from the file. */
  public void loadModel() throws Exception {

    BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(m_modelName));
    ObjectInputStream in = new ObjectInputStream(inStream);
    m_KEAFilter = (KEAFilter) in.readObject();
    in.close();
  }
Ejemplo n.º 24
0
  public ArrayList<FIncomePO> findAll() throws RemoteException {

    ArrayList<FIncomePO> incomeList = new ArrayList<FIncomePO>();

    FileInputStream fis = null;
    ObjectInputStream ois = null;
    try {
      fis = new FileInputStream(file);
      ois = new ObjectInputStream(fis);

      FIncomePO in = (FIncomePO) ois.readObject();

      while (fis.available() > 0) {
        byte[] buf = new byte[4];
        fis.read(buf);
        FIncomePO incomepo = (FIncomePO) ois.readObject();
        incomeList.add(incomepo);
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        ois.close();
      } catch (IOException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
      }
    }
    return incomeList;
  }
Ejemplo n.º 25
0
  static boolean loadDat(String path) {
    //        ByteArray byteArray = ByteArray.createByteArray(path);
    //        if (byteArray == null) return false;
    //
    //        int size = byteArray.nextInt(); // 这两个数组从byte转为int竟然要花4秒钟
    //        start = new int[size];
    //        for (int i = 0; i < size; ++i)
    //        {
    //            start[i] = byteArray.nextInt();
    //        }
    //
    //        size = byteArray.nextInt();
    //        pair = new int[size];
    //        for (int i = 0; i < size; ++i)
    //        {
    //            pair[i] = byteArray.nextInt();
    //        }

    try {
      ObjectInputStream in = new ObjectInputStream(new FileInputStream(path));
      start = (int[]) in.readObject();
      pair = (int[]) in.readObject();
      in.close();
    } catch (Exception e) {
      logger.warning("尝试载入缓存文件" + path + "发生异常[" + e + "],下面将载入源文件并自动缓存……");
      return false;
    }
    return true;
  }
Ejemplo n.º 26
0
  /**
   * Loads training set from the specified file
   *
   * @param filePath training set file
   * @return loded training set
   */
  public static DataSet load(String filePath) {
    ObjectInputStream oistream = null;

    try {
      File file = new File(filePath);
      if (!file.exists()) {
        throw new FileNotFoundException("Cannot find file: " + filePath);
      }

      oistream = new ObjectInputStream(new FileInputStream(filePath));
      DataSet tSet = (DataSet) oistream.readObject();

      return tSet;

    } catch (IOException ioe) {
      ioe.printStackTrace();
    } catch (ClassNotFoundException cnfe) {
      cnfe.printStackTrace();
    } finally {
      if (oistream != null) {
        try {
          oistream.close();
        } catch (IOException ioe) {
        }
      }
    }

    return null;
  }
Ejemplo n.º 27
0
 public FileCollectionSnapshot snapshot(FileCollection files) {
   try {
     File snapshotFile = cache.get(files);
     if (snapshotFile == null) {
       assert cache.size() == 0;
       FileCollectionSnapshot snapshot = snapshotter.snapshot(files);
       snapshotFile = new File(tmpDir, String.valueOf(cache.size()));
       ObjectOutputStream outstr =
           new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(snapshotFile)));
       try {
         outstr.writeObject(snapshot);
       } finally {
         outstr.close();
       }
       cache.put(files, snapshotFile);
       return snapshot;
     } else {
       ObjectInputStream instr =
           new ObjectInputStream(new BufferedInputStream(new FileInputStream(snapshotFile)));
       try {
         return (FileCollectionSnapshot) instr.readObject();
       } finally {
         instr.close();
       }
     }
   } catch (Exception e) {
     throw new UncheckedIOException(e);
   }
 }
Ejemplo n.º 28
0
  public void testSerial() {
    assertTrue(_nbhm.isEmpty());
    final String k1 = "k1";
    final String k2 = "k2";
    assertThat(_nbhm.put(k1, "v1"), nullValue());
    assertThat(_nbhm.put(k2, "v2"), nullValue());

    // Serialize it out
    try {
      FileOutputStream fos = new FileOutputStream("NBHM_test.txt");
      ObjectOutputStream out = new ObjectOutputStream(fos);
      out.writeObject(_nbhm);
      out.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Read it back
    try {
      File f = new File("NBHM_test.txt");
      FileInputStream fis = new FileInputStream(f);
      ObjectInputStream in = new ObjectInputStream(fis);
      NonBlockingIdentityHashMap nbhm = (NonBlockingIdentityHashMap) in.readObject();
      in.close();
      assertThat(
          "serialization works",
          nbhm.toString(),
          anyOf(is("{k1=v1, k2=v2}"), is("{k2=v2, k1=v1}")));
      if (!f.delete()) throw new IOException("delete failed");
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
  }
 /**
  * Because the readArchive() method requires unchecked casting, the compiler throws a warning at
  * compile time. Since we already know the data type we are extracting from the file we can safely
  * suppress this warning.
  */
 @SuppressWarnings("unchecked")
 public AbstractRoom[] readArchive() throws IOException, ClassNotFoundException {
   ObjectInputStream in = new ObjectInputStream(new FileInputStream("RoomArchive.txt"));
   roomArr = (AbstractRoom[]) in.readObject();
   in.close();
   return roomArr;
 }
Ejemplo n.º 30
0
  public static void main(String args[]) {
    List<User> users =
        Arrays.asList(
            new User("jack", 40), new User("john", 32), new User("jill", 47), new User("mike", 28));

    List<User> readUsers = null;

    try {
      ObjectOutputStream objWrite = new ObjectOutputStream(new FileOutputStream(output_fn));

      try {
        objWrite.writeObject(users);
        objWrite.flush();
      } finally {
        objWrite.close();
      }

      // Olion tietojen lukeminen
      ObjectInputStream objRead = new ObjectInputStream(new FileInputStream(output_fn));

      try {
        readUsers = (List<User>) objRead.readObject();
      } finally {
        objRead.close();
      }

    } catch (IOException | ClassNotFoundException ex) {
      System.out.println(ex);
    }
    for (User user : readUsers) {
      System.out.print(user.name + ": ");
      System.out.println(user.age);
    }
  }