static void serTest(Map s, int size) throws Exception { if (!(s instanceof Serializable)) return; System.out.print("Serialize : "); for (int i = 0; i < size; i++) { s.put(new Integer(i), Boolean.TRUE); } long startTime = System.currentTimeMillis(); FileOutputStream fs = new FileOutputStream("MapCheck.dat"); ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fs)); out.writeObject(s); out.close(); FileInputStream is = new FileInputStream("MapCheck.dat"); ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(is)); Map m = (Map) in.readObject(); long endTime = System.currentTimeMillis(); long time = endTime - startTime; System.out.print(time + "ms"); if (s instanceof IdentityHashMap) return; reallyAssert(s.equals(m)); }
public void testResultListSerializableComplex() throws Exception { // Create mutliple objects removeAll(Object.class); for (int i = 0; i < 20; i++) getStore().save(new Book("Learning Java 1." + i, "" + i)); for (int i = 0; i < 20; i++) getStore().save(new Referrer(i)); for (int i = 0; i < 20; i++) getStore().save(new User()); for (int i = 0; i < 20; i++) getStore().save(new MapHolder()); // Get the result list for all objects List result = getStore().find("find object"); Assert.assertEquals(result.size(), 80); // Now serialize ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream objectOut = new ObjectOutputStream(byteOut); objectOut.writeObject(result); objectOut.close(); // Close the store, let's pretend we're outside it tearDownStore(); try { // Deserialize ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream objectIn = new ObjectInputStream(byteIn); List deList = (List) objectIn.readObject(); // Test object Assert.assertEquals(deList.size(), 80); Assert.assertEquals(getCount(deList, Book.class), 20); Assert.assertEquals(getCount(deList, Referrer.class), 20); Assert.assertEquals(getCount(deList, User.class), 20); Assert.assertEquals(getCount(deList, MapHolder.class), 20); } finally { // Setup store for next tests setUpStore(); } }
private TaskObjectsExecutionResults runObject(TaskObjectsExecutionRequest obj) throws IOException, PDBatchTaskExecutorException { Object res = null; try { setAvailability(false); _oos.writeObject(obj); _oos.flush(); res = _ois.readObject(); setAvailability(true); } catch (IOException e) { // worker closed connection processException(e); throw e; } catch (ClassNotFoundException e) { processException(e); throw new IOException("stream has failed"); } if (res instanceof TaskObjectsExecutionResults) { _isPrevRunSuccess = true; return (TaskObjectsExecutionResults) res; } else { PDBatchTaskExecutorException e = new PDBatchTaskExecutorException("worker failed to run tasks"); if (_isPrevRunSuccess == false && !sameAsPrevFailedJob(obj._tasks)) { processException(e); // twice a loser, kick worker out } _isPrevRunSuccess = false; _prevFailedBatch = obj._tasks; throw e; } }
/** * Serialize an object to a byte array. (code by CB) * * @param object object to serialize * @return byte array that represents the object * @throws Exception */ public static byte[] toByte(Object object) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream((OutputStream) os); oos.writeObject(object); oos.close(); return os.toByteArray(); }
public void writeIndex(String location) { System.out.println("Writing index at: " + location); ObjectOutputStream objectOutputStream = null; try { File outputFile = new File(location); if (!outputFile.exists()) { outputFile.getParentFile().mkdirs(); outputFile.createNewFile(); } OutputStream file = new FileOutputStream(outputFile); BufferedOutputStream buffer = new BufferedOutputStream(file); objectOutputStream = new ObjectOutputStream(buffer); objectOutputStream.writeObject(tokenCountMap); objectOutputStream.writeObject(references); } catch (IOException ex) { System.out.println( "\nError writing index for " + author.getName() + " at location " + location); } finally { if (objectOutputStream != null) try { objectOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** * 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; }
public void serializeAndReplace(Object obj) throws IOException { FileOutputStream fOut = new FileOutputStream(this.getFilepath()); ObjectOutputStream objOut = new ObjectOutputStream(fOut); objOut.writeObject(obj); objOut.close(); fOut.close(); }
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); } }
/** * Serializes the passed object to a byte array, returning a zero byte array if the passed object * is null, or fails serialization * * @param arg The object to serialize * @return the serialized object */ public static byte[] serializeNoCompress(Object arg) { if (arg == null) return new byte[] {}; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(baos); oos.writeObject(arg); oos.flush(); baos.flush(); return baos.toByteArray(); } catch (Exception ex) { return new byte[] {}; } finally { try { baos.close(); } catch (Exception ex) { /* No Op */ } if (oos != null) try { oos.close(); } catch (Exception ex) { /* No Op */ } } }
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(); } }
// add the new user to the encrypted users file which has the detailed stats for all users // synchronize to make sure that only one thread can be inside this block at a time. public static synchronized String addUserAndIssueCode(UserStats stats) throws IOException, GeneralSecurityException, ClassNotFoundException, NoMoreCodesException { // ok, now we have a list of stats objects, representing all users. // add this user to the list. // the code assigned to this user will simply be codes.get(users.size()) // but do an error check first to be sure we're not out of codes List<UserStats> users = readUsersFile(); if (users.size() >= MemoryStudy.codes.size()) { log.warn("NOC WARNING: codes file exhausted!!!!"); throw new NoMoreCodesException(); } // ok, we have enough codes, just give out one String passkey = MemoryStudy.codes.get(users.size()); int USERID_BASE = 100; // userid numbering starts from USERID_BASE, new id is base + # existing codes stats.userid = Integer.toString(USERID_BASE + users.size()); stats.code = passkey; users.add(stats); // encrypt and write the users file back ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(users); oos.close(); CryptoUtils.writeEncryptedBytes(baos.toByteArray(), USERS_FILE); return passkey; }
public static void saveObjectToFile(String fileName, Object obj) throws Exception { FileOutputStream ostream = new FileOutputStream(fileName); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeObject(obj); p.flush(); ostream.close(); }
public static void main(String[] args) { Random r = new Random(); int n; if (args.length == 1) { n = Integer.parseInt(args[0]); } else { n = r.nextInt(10000) + 1; } try { OutputStream ofs = new FileOutputStream("scores.txt"); ObjectOutputStream oos = new ObjectOutputStream(ofs); for (int i = 0; i < n; ++i) { int testNum = r.nextInt(21); String name = randString(r.nextInt(6) + 5); while (testNum-- > 0) { oos.writeUTF(name); oos.writeInt(r.nextInt(101)); } } ofs.close(); } catch (Exception e) { System.out.println("Error creating scores.txt: " + e.getMessage()); } try { InputStream ifs = new FileInputStream("scores.txt"); String name = findStudentWithTopThreeAverageScores(ifs); System.out.println("top student is " + name); ifs.close(); } catch (Exception e) { System.out.println("Error reading scores.txt: " + e.getMessage()); } }
/** Method: readFromFile() */ @Test public void testReadFromFile() 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); try { FileOutputStream fileOut = new FileOutputStream("gameStats.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(testLLGN); out.close(); fileOut.close(); } catch (IOException e) { } testScoreboard.readFromFile(); assertTrue( "Is a public method that returns void and only alters a private variable with no getter. Should be made" + " a private method, should allow for ScoreInfo access or should not be tested", false); }
public void InsertSupplier(Supplier supplier) { FileOutputStream fos = null; try { File file = new File("Suppliers.dat"); if (file.exists()) { fos = new FileOutputStream(file, true); _aoos = new AppendableObjectOutputStream(fos); _aoos.writeObject(supplier); System.out.println("Fornecedor cadastrado com sucesso!"); } else { fos = new FileOutputStream(file); _oos = new ObjectOutputStream(fos); _oos.writeObject(supplier); System.out.println("Fornecedor cadastrado com sucesso!"); } } catch (IOException ex) { System.out.println("Falha ao cadastrar fornecedor!"); ex.getStackTrace(); } finally { try { if (_aoos != null) _aoos.close(); if (_oos != null) _oos.close(); if (fos != null) fos.close(); } catch (IOException ex) { System.out.println("Falha ao cadastrar fornecedor!"); ex.getStackTrace(); } } }
static boolean saveDat(String path) { try { // DataOutputStream out = new DataOutputStream(new FileOutputStream(path)); // out.writeInt(start.length); // for (int i : start) // { // out.writeInt(i); // } // out.writeInt(pair.length); // for (int i : pair) // { // out.writeInt(i); // } // out.close(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path)); out.writeObject(start); out.writeObject(pair); out.close(); } catch (Exception e) { logger.log(Level.WARNING, "在缓存" + path + "时发生异常", e); return false; } return true; }
private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); out.writeObject(prefix); out.writeInt(gramSizes.length); for (int i = 0; i < gramSizes.length; i++) out.writeInt(gramSizes[i]); out.writeBoolean(distinguishBorders); }
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(); } }
/** Создаёт новый файл для хранения долговременной информации */ public static void createNewData() throws IOException { if (ApplicationProperties.BUY_FILE.createNewFile()) { ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(ApplicationProperties.BUY_FILE)); os.writeObject(new ApplicationService()); } }
@Override public void execute(JavaExecSpec javaExec) { configureReloadAgent(javaExec); // mutates the launch context OutputStream fileOut = null; ObjectOutputStream oos = null; try { fileOut = new FileOutputStream(contextDestination); oos = new ObjectOutputStream(fileOut); oos.writeObject(launchContext); javaExec.setWorkingDir(launchContext.getBaseDir()); if (launchContext.getGrailsHome() != null) { javaExec.systemProperty("grails.home", launchContext.getGrailsHome().getAbsolutePath()); } File launcherJar = findJarFile(ForkedGrailsLauncher.class); javaExec.classpath(launcherJar); javaExec.setMain(Main.class.getName()); javaExec.args(contextDestination.getAbsolutePath()); } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (oos != null) { oos.close(); } if (fileOut != null) { fileOut.close(); } } catch (IOException ignore) { } } }
public static void main(String[] args) { String str; Socket sock = null; ObjectOutputStream writer = null; Scanner kb = new Scanner(System.in); try { sock = new Socket("127.0.0.1", 4445); } catch (IOException e) { System.out.println("Could not connect."); System.exit(-1); } try { writer = new ObjectOutputStream(sock.getOutputStream()); } catch (IOException e) { System.out.println("Could not create write object."); System.exit(-1); } str = kb.nextLine(); try { writer.writeObject(str); writer.flush(); } catch (IOException e) { System.out.println("Could not write to buffer"); System.exit(-1); } try { sock.close(); } catch (IOException e) { System.out.println("Could not close connection."); System.exit(-1); } System.out.println("Wrote and exited successfully"); }
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); } }
public void run() { try { ObjectOutputStream outputStream = new ObjectOutputStream(_clientSocket.getOutputStream()); outputStream.flush(); DataInputStream inputStream = new DataInputStream(_clientSocket.getInputStream()); while (true) { String request = inputStream.readUTF(); Trace.info("Received request: " + request); RMResult response = processIfComposite(request); if (response == null) { response = processIfCIDRequired(request); if (response == null) { response = processAtomicRequest(request); } } outputStream.writeObject(response); outputStream.flush(); } } catch (EOFException eof) { Trace.info("A client closed a connection."); } catch (IOException e) { e.printStackTrace(); } }
public static void main1(String[] args) throws IOException, ClassNotFoundException { Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1); Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15); carl.setSecretary(harry); Manager tony = new Manager("Tony Tester", 40000, 1990, 3, 15); tony.setSecretary(harry); Employee[] staff = new Employee[3]; staff[0] = carl; staff[1] = harry; staff[2] = tony; // save all employee records to the file employee.dat try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.dat"))) { out.writeObject(staff); } try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.dat"))) { // retrieve all records into a new array Employee[] newStaff = (Employee[]) in.readObject(); // raise secretary's salary newStaff[1].raiseSalary(10); // print the newly read employee records for (Employee e : newStaff) System.out.println(e); } }
public void updateFile() { ArrayList<Product> products = new ArrayList<Product>(); try { // products.clear(); Statement s = connection.createStatement(); // ((org.postgresql.jdbc3.AbstractJdbc3Statement)s).setQueryTimeout(1); String sql = "select * from stock"; // ResultSet // resultset=((org.postgresql.jdbc3.AbstractJdbc3Statement)s).executeQuery(sql); ResultSet resultset = s.executeQuery(sql); // searchResult.clear(); while (resultset.next()) { int id = resultset.getInt(1); String pname = resultset.getString(2); int amount = resultset.getInt(3); double price = resultset.getDouble(4); String feature = resultset.getString(5); products.add(new Product(id, pname, amount, price, feature)); } System.out.println(products.size() + "beforewrite"); oout = new ObjectOutputStream(new FileOutputStream(file)); oout.writeObject(products); oout.close(); System.out.println("all written"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void createDB() throws IOException { File db = new File(dbLocation); ObjectOutputStream w = new ObjectOutputStream(new FileOutputStream(dbLocation)); w.writeObject(digestDB); w.flush(); w.close(); }
private void handleKeepAlive() { Connection c = null; try { netCode = ois.readInt(); c = checkConnectionNetCode(); if (c != null && c.getState() == Connection.STATE_CONNECTED) { oos.writeInt(ACK_KEEP_ALIVE); oos.flush(); System.out.println("->ACK_KEEP_ALIVE"); // $NON-NLS-1$ } else { System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$ oos.writeInt(NOT_CONNECTED); oos.flush(); } } catch (IOException e) { System.out.println("handleKeepAlive: " + e.getMessage()); // $NON-NLS-1$ if (c != null) { c.setState(Connection.STATE_DISCONNECTED); System.out.println( "Connection closed with " + c.getRemoteAddress() + //$NON-NLS-1$ ":" + c.getRemotePort()); // $NON-NLS-1$ } } }
/** * 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; }
public byte[] serialize(Object data) throws SharedMemorySerializationException { try { if (data == null) { return new byte[0]; } int type = getType(data); switch (type) { case JAVA_OBJECT: { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(data); return byteArrayOutputStream.toByteArray(); } case STRING: { return ((String) data).getBytes(DBProperties.getCharset()); } case INTEGER: { byte[] array = new byte[SIZE_OF_INT]; SerializationUtils.intByteArrayFiller((Integer) data, array, 0); return array; } default: throw new SharedMemorySerializationException( CommandStatus.unExpectedException, "Fail to serialize object : " + data); } } catch (IOException e) { throw new SharedMemorySerializationException( CommandStatus.unExpectedException, "Fail to serialize object : " + data); } }
public void windowClosing(WindowEvent e) // write file on finish { FileOutputStream out = null; ObjectOutputStream data = null; try { // open file for output out = new FileOutputStream(DB); data = new ObjectOutputStream(out); // write Person objects to file using iterator class Iterator<Person> itr = persons.iterator(); while (itr.hasNext()) { data.writeObject((Person) itr.next()); } data.flush(); data.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( objUpdate.this, "Error processing output file" + "\n" + ex.toString(), "Output Error", JOptionPane.ERROR_MESSAGE); } finally { System.exit(0); } }