List of usage examples for java.io ObjectInputStream close
public void close() throws IOException
From source file:maui.main.MauiTopicExtractor.java
/** * Loads the extraction model from the file. */// ww w .j ava2 s. c om public void loadModel() throws Exception { BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(modelName)); ObjectInputStream in = new ObjectInputStream(inStream); mauiFilter = (MauiFilter) in.readObject(); // If TFxIDF values are to be computed from the test corpus if (buildGlobalDictionary == true) { if (debugMode) { System.err.println("-- The global dictionaries will be built from this test collection.."); } mauiFilter.globalDictionary = null; } in.close(); }
From source file:com.adjust.sdk.PackageHandler.java
private void readPackageQueue() { if (dropOfflineActivities) { packageQueue = new ArrayList<ActivityPackage>(); return; // don't read old packages when offline tracking is disabled }/*from ww w . jav a 2 s.c o m*/ try { FileInputStream inputStream = context.openFileInput(PACKAGE_QUEUE_FILENAME); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); ObjectInputStream objectStream = new ObjectInputStream(bufferedStream); try { Object object = objectStream.readObject(); @SuppressWarnings("unchecked") List<ActivityPackage> packageQueue = (List<ActivityPackage>) object; logger.debug("Package handler read %d packages", packageQueue.size()); this.packageQueue = packageQueue; return; } catch (ClassNotFoundException e) { logger.error("Failed to find package queue class"); } catch (OptionalDataException e) { /* no-op */ } catch (IOException e) { logger.error("Failed to read package queue object"); } catch (ClassCastException e) { logger.error("Failed to cast package queue object"); } finally { objectStream.close(); } } catch (FileNotFoundException e) { logger.verbose("Package queue file not found"); } catch (Exception e) { logger.error("Failed to read package queue file"); } // start with a fresh package queue in case of any exception packageQueue = new ArrayList<ActivityPackage>(); }
From source file:junk.gui.HazardDataSetCalcCondorApp.java
/** * sets up the connection with the servlet on the server (gravity.usc.edu) *///from ww w . j a va2 s . c om private void sendParametersToServlet(SitesInGriddedRegion regionSites, ScalarIntensityMeasureRelationshipAPI imr, String eqkRupForecastLocation) { try { if (D) System.out.println("starting to make connection with servlet"); URL hazardMapServlet = new URL(SERVLET_URL); URLConnection servletConnection = hazardMapServlet.openConnection(); if (D) System.out.println("connection established"); // inform the connection that we will send output and accept input servletConnection.setDoInput(true); servletConnection.setDoOutput(true); // Don't use a cached version of URL connection. servletConnection.setUseCaches(false); servletConnection.setDefaultUseCaches(false); // Specify the content type that we will send binary data servletConnection.setRequestProperty("Content-Type", "application/octet-stream"); ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream()); //sending the object of the gridded region sites to the servlet toServlet.writeObject(regionSites); //sending the IMR object to the servlet toServlet.writeObject(imr); //sending the EQK forecast object to the servlet toServlet.writeObject(eqkRupForecastLocation); //send the X values in a arraylist ArrayList list = new ArrayList(); for (int i = 0; i < function.getNum(); ++i) list.add(new String("" + function.getX(i))); toServlet.writeObject(list); // send the MAX DISTANCE toServlet.writeObject(maxDistance); //sending email address to the servlet toServlet.writeObject(emailText.getText()); //sending the parameters info. to the servlet toServlet.writeObject(getParametersInfo()); //sending the dataset id to the servlet toServlet.writeObject(datasetIdText.getText()); toServlet.flush(); toServlet.close(); // Receive the datasetnumber from the servlet after it has received all the data ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream()); String dataset = fromServlet.readObject().toString(); JOptionPane.showMessageDialog(this, dataset); if (D) System.out.println("Receiving the Input from the Servlet:" + dataset); fromServlet.close(); } catch (Exception e) { ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo()); bugWindow.setVisible(true); bugWindow.pack(); } }
From source file:br.org.acessobrasil.nucleuSilva.util.ObterPaginaLocal.java
/** * Mtodo que extra o contedo de uma pgina web. * @param relatorio Pgina que vai ser pesquisada. * @throws IOException Erro ao tentar extrair o contedo da pgina html. *//*from w ww .j av a 2s . co m*/ public void getContent(final RelatorioDaUrl relatorio) { final int mb = 1024; try { StringBuilder sbd = null; sbd = new StringBuilder(); FileInputStream fis = null; ObjectInputStream ois = null; try { //JOptionPane.showMessageDialog(null,"arq = " + relatorio.getUrl()); File file = new File(relatorio.getUrl()); // JOptionPane.showMessageDialog(null,"fileexist"); if (file.exists()) { fis = new FileInputStream(file); byte[] dados = new byte[mb]; int bytesLidos = 0; while ((bytesLidos = fis.read(dados)) > 0) { sbd.append(new String(dados, 0, bytesLidos)); } fis.close(); } } catch (Exception e) { log.error(e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } } if (ois != null) { try { ois.close(); } catch (Exception e) { } } } if (sbd != null) { relatorio.setConteudo(sbd); } } catch (Exception e) { log.error(e.getMessage(), e); } }
From source file:hu.tbognar76.apking.ApKing.java
private void readPhoneCache() { try {/*from ww w . j av a 2s . co m*/ FileInputStream fileIn = new FileInputStream(this.init.phoneCache); ObjectInputStream in = new ObjectInputStream(fileIn); @SuppressWarnings("unchecked") ArrayList<DeviceApp> readObject = (ArrayList<DeviceApp>) in.readObject(); this.dmanager.apps = readObject; in.close(); fileIn.close(); // System.out.println("Cache loaded: " + this.serialCache + // " cache size: " + this.serialInHash.size()); } catch (IOException i) { System.out.println("No Cache!!"); return; } catch (ClassNotFoundException c) { c.printStackTrace(); return; } }
From source file:com.splicemachine.derby.serialization.ActivationSerializerTest.java
@Test public void canSerdeStatementTextLargerThanUTF8Limit() throws Exception { ObjectOutputStream oos = null; ObjectInputStream ois = null; try {//from ww w .j ava 2 s.c o m StringBuilder sb = new StringBuilder(); for (int i = 0; i < 65535 + 1; i++) { sb.append('A'); } SpliceObserverInstructions.ActivationContext context = new SpliceObserverInstructions.ActivationContext( null, true, true, sb.toString(), false, 100, "foo".getBytes()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); context.writeExternal(oos); oos.flush(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ois = new ObjectInputStream(bais); SpliceObserverInstructions.ActivationContext context2 = new SpliceObserverInstructions.ActivationContext(); context2.readExternal(ois); Assert.assertEquals("Serde Incorrect", context.getStatementTxt(), context2.getStatementTxt()); } finally { if (oos != null) oos.close(); if (ois != null) ois.close(); } }
From source file:edu.usf.cutr.opentripplanner.android.util.JacksonConfig.java
/** * Read the given object from Android internal storage for this app * * @param objectType object type, defined by class constant Strings, to retrieve * from cache (ObjectReader, ObjectMapper, or XmlReader) * @return deserialized Object, or null if object couldn't be deserialized *///from w ww.j a va 2s . c om private static synchronized Serializable readFromCache(String objectType) { FileInputStream fileStream = null; ObjectInputStream objectStream = null; // Holds object to be read from cache Serializable object = null; // Before reading from cache, check to make sure that we don't already // have the requested object in memory if (objectType.equalsIgnoreCase(OBJECT_MAPPER) && mapper != null) { return mapper; } if (objectType.equalsIgnoreCase(OBJECT_READER) && reader != null) { return reader; } if (context != null) { try { String fileName = objectType + CACHE_FILE_EXTENSION; cacheReadStartTime = System.nanoTime(); fileStream = context.openFileInput(fileName); objectStream = new ObjectInputStream(fileStream); object = (Serializable) objectStream.readObject(); cacheReadEndTime = System.nanoTime(); // Get size of serialized object long fileSize = context.getFileStreamPath(fileName).length(); Log.d("TAG", "Read " + fileName + " from cache (" + fileSize + " bytes) in " + df.format(getLastCacheReadTime()) + " ms."); } catch (FileNotFoundException e) { Log.w(TAG, "Cache miss - Jackson object '" + objectType + "' does not exist in app cache: " + e); return null; } catch (Exception e) { // Reset timestamps to show there was an error cacheReadStartTime = 0; cacheReadEndTime = 0; Log.e(TAG, "Couldn't read Jackson object '" + objectType + "' from cache: " + e); } finally { try { if (objectStream != null) { objectStream.close(); } if (fileStream != null) { fileStream.close(); } } catch (Exception e) { Log.e(TAG, "Error closing cache file connections: " + e); } } if (object instanceof ObjectMapper) { mapper = (ObjectMapper) object; } if (object instanceof ObjectReader) { reader = (ObjectReader) object; } return object; } else { Log.w(TAG, "Couldn't read from cache - no context provided. If you want to use the cache, call JacksonConfig.setUsingCache(true, context) with a reference to your context."); return null; } }
From source file:com.moscona.dataSpace.persistence.DirectoryDataStore.java
public DataSpace loadDataSpace(IMemoryManager memoryManager) throws DataSpaceException { stats.startTimerFor(TIMING_LOAD_DATA_SPACE); try {//from www.j a v a 2s . c om DataSpace dataSpace = null; InputStream in = new FileInputStream(dataSpaceFileName()); try { ObjectInputStream objIn = new ObjectInputStream(in); try { dataSpace = (DataSpace) objIn.readObject(); dataSpace.initTransientsAfterRestore(this, memoryManager); register(dataSpace); } finally { objIn.close(); } } finally { in.close(); } return dataSpace; } catch (Exception e) { throw new DataSpaceException( "Exception while restoring data space from " + dataSpaceFileName() + ": " + e, e); } finally { stopTimerFor(TIMING_LOAD_DATA_SPACE); } }
From source file:foodsimulationmodel.pathmapping.Route.java
/** * Used to create a new BuildingsOnRoadCache object. This function is used instead of the constructor directly so * that the class can check if there is a serialised version on disk already. If not then a new one is created and * returned.// w w w. j a v a 2s. c o m * * @param buildingEnv * @param buildingsFile * @param roadEnv * @param roadsFile * @param serialisedLoc * @param geomFac * @return * @throws Exception */ public synchronized static NearestRoadCoordCache getInstance(Geography<IAgent> buildingEnv, File buildingsFile, Geography<Road> roadEnv, File roadsFile, File serialisedLoc, GeometryFactory geomFac) throws Exception { double time = System.nanoTime(); // See if there is a cache object on disk. if (serialisedLoc.exists()) { FileInputStream fis = null; ObjectInputStream in = null; NearestRoadCoordCache ncc = null; try { fis = new FileInputStream(serialisedLoc); in = new ObjectInputStream(fis); ncc = (NearestRoadCoordCache) in.readObject(); in.close(); // Check that the cache is representing the correct data and the // modification dates are ok if (!buildingsFile.getAbsolutePath().equals(ncc.buildingsFile.getAbsolutePath()) || !roadsFile.getAbsolutePath().equals(ncc.roadsFile.getAbsolutePath()) || buildingsFile.lastModified() > ncc.createdTime || roadsFile.lastModified() > ncc.createdTime) { LOGGER.log(Level.FINE, "BuildingsOnRoadCache, found serialised object but it doesn't match the " + "data (or could have different modification dates), will create a new cache."); } else { LOGGER.log(Level.FINER, "NearestRoadCoordCache, found serialised cache, returning it (in " + 0.000001 * (System.nanoTime() - time) + "ms)"); return ncc; } } catch (IOException ex) { if (serialisedLoc.exists()) serialisedLoc.delete(); // delete to stop problems loading incomplete file next tinme throw ex; } catch (ClassNotFoundException ex) { if (serialisedLoc.exists()) serialisedLoc.delete(); throw ex; } } // No serialised object, or got an error when opening it, just create a new one return new NearestRoadCoordCache(buildingEnv, buildingsFile, roadEnv, roadsFile, serialisedLoc, geomFac); }
From source file:foodsimulationmodel.pathmapping.Route.java
/** * Used to create a new BuildingsOnRoadCache object. This function is used instead of the constructor directly so * that the class can check if there is a serialised version on disk already. If not then a new one is created and * returned.//from w w w . j a v a 2 s . c om * * @param buildingEnv * @param buildingsFile * @param roadEnv * @param roadsFile * @param serialisedLoc * @param geomFac * @return * @throws Exception */ public synchronized static BuildingsOnRoadCache getInstance(Geography<IAgent> buildingEnv, File buildingsFile, Geography<Road> roadEnv, File roadsFile, File serialisedLoc, GeometryFactory geomFac) throws Exception { double time = System.nanoTime(); // See if there is a cache object on disk. if (serialisedLoc.exists()) { FileInputStream fis = null; ObjectInputStream in = null; BuildingsOnRoadCache bc = null; try { fis = new FileInputStream(serialisedLoc); in = new ObjectInputStream(fis); bc = (BuildingsOnRoadCache) in.readObject(); in.close(); // Check that the cache is representing the correct data and the // modification dates are ok // (WARNING, if this class is re-compiled the serialised object // will still be read in). if (!buildingsFile.getAbsolutePath().equals(bc.buildingsFile.getAbsolutePath()) || !roadsFile.getAbsolutePath().equals(bc.roadsFile.getAbsolutePath()) || buildingsFile.lastModified() > bc.createdTime || roadsFile.lastModified() > bc.createdTime) { LOGGER.log(Level.FINER, "BuildingsOnRoadCache, found serialised object but it doesn't match the " + "data (or could have different modification dates), will create a new cache."); } else { // Have found a useable serialised cache. Now use the cached // list of id's to construct a // new cache of buildings and roads. // First need to buld list of existing roads and buildings Hashtable<String, Road> allRoads = new Hashtable<String, Road>(); for (Road r : roadEnv.getAllObjects()) allRoads.put(r.getIdentifier(), r); Hashtable<String, IAgent> allBuildings = new Hashtable<String, IAgent>(); for (IAgent b : buildingEnv.getAllObjects()) allBuildings.put(b.getIdentifier(), b); // Now create the new cache theCache = new Hashtable<Road, ArrayList<IAgent>>(); for (String roadId : bc.referenceCache.keySet()) { ArrayList<IAgent> buildings = new ArrayList<IAgent>(); for (String buildingId : bc.referenceCache.get(roadId)) { buildings.add(allBuildings.get(buildingId)); } theCache.put(allRoads.get(roadId), buildings); } LOGGER.log(Level.FINER, "BuildingsOnRoadCache, found serialised cache, returning it (in " + 0.000001 * (System.nanoTime() - time) + "ms)"); return bc; } } catch (IOException ex) { if (serialisedLoc.exists()) serialisedLoc.delete(); // delete to stop problems loading incomplete file next tinme throw ex; } catch (ClassNotFoundException ex) { if (serialisedLoc.exists()) serialisedLoc.delete(); throw ex; } } // No serialised object, or got an error when opening it, just create a // new one return new BuildingsOnRoadCache(buildingEnv, buildingsFile, roadEnv, roadsFile, serialisedLoc, geomFac); }