List of usage examples for java.io ObjectOutputStream flush
public void flush() throws IOException
From source file:org.shaman.database.Benchmark.java
/** * prints the file size//from ww w. j a v a 2 s . c om * @param roots the roots from the different passes */ private void printFileSizes(Record... roots) throws IOException { //result array int size; String format = "%1$,11d"; System.out.println("passes database serial compressed xml"); //save it for (int i = 0; i < roots.length; i++) { Record root = roots[i]; System.out.print("pass " + (i + 1) + " "); //database ArrayOutput ao = new ArrayOutput(); Database db = new Database(root); db.save(ao, FailOnErrorHandler.INSTANCE); size = ao.getTotalSize(); System.out.printf(format, size); System.out.print("B "); //uncompressed serialization CountingOutputStream out = new CountingOutputStream(new NullOutputStream()); ObjectOutputStream dos = new ObjectOutputStream(out); dos.writeObject(root); dos.flush(); size = out.getCount(); System.out.printf(format, size); System.out.print("B "); //compressed serialization out.resetCount(); dos = new ObjectOutputStream(new GZIPOutputStream(out)); dos.writeObject(root); dos.flush(); size = out.getCount(); System.out.printf(format, size); System.out.print("B "); //xml out.resetCount(); XMLEncoder xml = new XMLEncoder(out); xml.writeObject(root); xml.flush(); size = out.getCount(); System.out.printf(format, size); System.out.println("B"); } }
From source file:com.joliciel.talismane.machineLearning.AbstractMachineLearningModel.java
@Override public final void persist(File modelFile) { try {// w w w .j av a 2 s . c om ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFile, false)); Writer writer = new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); zos.putNextEntry(new ZipEntry("algorithm.txt")); writer.write(this.getAlgorithm().name()); writer.flush(); zos.flush(); for (String descriptorKey : descriptors.keySet()) { zos.putNextEntry(new ZipEntry(descriptorKey + "_descriptors.txt")); List<String> descriptorList = descriptors.get(descriptorKey); for (String descriptor : descriptorList) { writer.write(descriptor + "\n"); writer.flush(); } zos.flush(); } zos.putNextEntry(new ZipEntry("attributes.txt")); for (String name : this.modelAttributes.keySet()) { String value = this.modelAttributes.get(name); writer.write(name + "\t" + value + "\n"); writer.flush(); } for (String name : this.dependencies.keySet()) { Object dependency = this.dependencies.get(name); zos.putNextEntry(new ZipEntry(name + "_dependency.obj")); ObjectOutputStream oos = new ObjectOutputStream(zos); try { oos.writeObject(dependency); } finally { oos.flush(); } zos.flush(); } this.persistOtherEntries(zos); if (this.externalResources != null) { zos.putNextEntry(new ZipEntry("externalResources.obj")); ObjectOutputStream oos = new ObjectOutputStream(zos); try { oos.writeObject(externalResources); } finally { oos.flush(); } zos.flush(); } this.writeDataToStream(zos); zos.putNextEntry(new ZipEntry("model.bin")); this.writeModelToStream(zos); zos.flush(); zos.close(); } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:deepschema.ExtractingTool.java
/** * Caches classes and subclasses to file. * //from ww w .ja v a2 s.com * @param operation : "read" or "write" */ @SuppressWarnings("unchecked") void cache(String action) { final String cacheFile = ".cache"; try { switch (action) { case "read": { ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(cacheFile)); classes = (Map<Integer, WikidataClassProperties>) ((ObjectInputStream) objectInputStream) .readObject(); instances = (Map<Integer, WikidataInstanceProperties>) ((ObjectInputStream) objectInputStream) .readObject(); objectInputStream.close(); } case "write": { ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(cacheFile)); objectOutputStream.writeObject(classes); objectOutputStream.writeObject(instances); objectOutputStream.flush(); objectOutputStream.close(); } } } catch (ClassNotFoundException | IOException e) { System.err.println("Problem while reading/writing from/to cache."); e.printStackTrace(); } }
From source file:edu.umass.cs.msocket.common.policies.GeoLoadProxyPolicy.java
/** * @throws Exception if a GNS error occurs * @see edu.umass.cs.msocket.common.policies.ProxySelectionPolicy#getNewProxy() *///from ww w . j a v a2 s .c o m @Override public List<InetSocketAddress> getNewProxy() throws Exception { // Lookup for active location service GUIDs final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient(); final GuidEntry guidEntry = gnsCredentials.getGuidEntry(); JSONArray guids; try { guids = gnsClient.fieldRead(proxyGroupName, GnsConstants.ACTIVE_LOCATION_FIELD, guidEntry); } catch (Exception e) { throw new GnsException("Could not find active location services (" + e + ")"); } // Try every location proxy in the list until one works for (int i = 0; i < guids.length(); i++) { // Retrieve the location service IP and connect to it String locationGuid = guids.getString(i); String locationIP = gnsClient.fieldRead(locationGuid, GnsConstants.LOCATION_SERVICE_IP, guidEntry) .getString(0); logger.fine("Contacting location service " + locationIP + " to request " + numProxies + " proxies"); // Location IP is stored as host:port StringTokenizer st = new StringTokenizer(locationIP, ":"); try { // Protocol is send the number of desired proxies and receive strings // containing proxy IP:port Socket s = new Socket(st.nextToken(), Integer.parseInt(st.nextToken())); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); oos.writeInt(numProxies); oos.flush(); List<InetSocketAddress> result = new LinkedList<InetSocketAddress>(); while (!s.isClosed() && result.size() < numProxies) { String proxyIP = ois.readUTF(); StringTokenizer stp = new StringTokenizer(proxyIP, ":"); result.add(new InetSocketAddress(stp.nextToken(), Integer.parseInt(stp.nextToken()))); } if (!s.isClosed()) // We receive all the proxies we need, just close the // socket s.close(); return result; } catch (Exception e) { logger.info("Failed to obtain proxy from location service" + locationIP + " (" + e + ")"); } } throw new GnsException("Could not find any location service to provide a geolocated proxy"); }
From source file:org.hyperledger.fabric.sdk.Member.java
/** * Save the state of this member to the key value store. *//*ww w. j a v a 2 s . c o m*/ public void saveState() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); oos.flush(); keyValStore.setValue(keyValStoreName, Hex.toHexString(bos.toByteArray())); bos.close(); } catch (IOException e) { logger.debug(String.format("Could not save state of member %s", this.name), e); } }
From source file:edu.usf.cutr.siri.util.SiriUtils.java
/** * Write the given object to Android internal storage for this app * //from w ww .j ava 2 s . c o m * @param object * serializable object to be written to cache (ObjectReader, * ObjectMapper, or XmlReader) * @return true if object was successfully written to cache, false if it was * not */ private synchronized static boolean writeToCache(Serializable object) { FileOutputStream fileStream = null; ObjectOutputStream objectStream = null; String fileName = ""; boolean success = false; try { if (object instanceof XmlMapper) { fileName = XML_MAPPER + CACHE_FILE_EXTENSION; } else if (object instanceof ObjectMapper) { // ObjectMapper check must come after XmlMapper check, // since XmlMapper is subclass of ObjectMapper fileName = OBJECT_MAPPER + CACHE_FILE_EXTENSION; } else if (object instanceof ObjectReader) { fileName = OBJECT_READER + CACHE_FILE_EXTENSION; } cacheWriteStartTime = System.nanoTime(); fileStream = new FileOutputStream(fileName); objectStream = new ObjectOutputStream(fileStream); objectStream.writeObject(object); objectStream.flush(); fileStream.getFD().sync(); cacheWriteEndTime = System.nanoTime(); success = true; // Get size of serialized object File file = new File(fileName); long fileSize = file.length(); System.out.println("Wrote " + fileName + " to cache (" + fileSize + " bytes) in " + df.format(getLastCacheWriteTime() / 1000000.0) + " ms."); } catch (IOException e) { // Reset timestamps to show there was an error cacheWriteStartTime = 0; cacheWriteEndTime = 0; System.out.println("Couldn't write object to cache: " + e); e.printStackTrace(); } finally { try { if (objectStream != null) { objectStream.close(); } if (fileStream != null) { fileStream.close(); } } catch (Exception e) { System.out.println("Error closing file connections: " + e); } } return success; }
From source file:com.all.dht.util.DhtFileUtils.java
public void persistObjectToFile(Serializable object, String routeTableFile) throws IOException { ObjectOutputStream out = new ObjectOutputStream( new BufferedOutputStream(new SecureOutputStream(new FileOutputStream(routeTableFile)))); out.writeObject(object);/*from w ww . ja va2s . com*/ out.flush(); out.close(); }
From source file:com.nebhale.jsonpath.JsonPathTest.java
@Test public void serializable() throws IOException, ClassNotFoundException { assertTrue(Serializable.class.isAssignableFrom(JsonPath.class)); JsonPath jsonPath = JsonPath.compile("$.store.book[0].title"); assertEquals("Sayings of the Century", jsonPath.read(STRING_VALID, String.class)); byte[] serialized; ObjectOutputStream out = null; try {//from ww w. j av a2s . c o m ByteArrayOutputStream bytes = new ByteArrayOutputStream(); out = new ObjectOutputStream(bytes); out.writeObject(jsonPath); out.flush(); serialized = bytes.toByteArray(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } } JsonPath newJsonPath; ObjectInputStream in = null; try { in = new ObjectInputStream(new ByteArrayInputStream(serialized)); newJsonPath = (JsonPath) in.readObject(); } finally { if (in != null) { in.close(); } } assertEquals("Sayings of the Century", newJsonPath.read(STRING_VALID, String.class)); }
From source file:com.hs.mail.smtp.message.SmtpMessage.java
public void store() throws IOException { File file = getControlFile(); ObjectOutputStream os = null; try {/*w w w. j a va2s.c o m*/ OutputStream out = new BufferedOutputStream(new FileOutputStream(file), 1024 * 4); os = new ObjectOutputStream(out); os.writeObject(this); os.flush(); } finally { IOUtils.closeQuietly(os); } }