Java Code Examples for java.io.ObjectOutputStream.close()

The following are Jave code examples for showing how to use close() of the java.io.ObjectOutputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: 360w17g1   File: AbstractController.java   View Source Code Vote up 6 votes
/**
 * Serializes an object and writes it to the disk.
 * <p>The file written will match the pattern "KEYNAME_CLASSNAME.ser"</p>
 * 
 * @param theKey the key name associated with the object
 * @param theObject the object to serialize
 * @return true if the operation completed successfully
 */
public static final <E extends Serializable> boolean serializeToDisk(final String theKey, final E theObject) {
	boolean succeeded;
	try {
		final File file = new File(theKey + "_" + theObject.getClass().getSimpleName() + ".ser");
		if (!file.exists()) {
			file.createNewFile();
		}
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
		oos.writeObject(theObject);
		oos.close();
		succeeded = true;
	} catch (final Exception theException) {
		//System.err.println(theException.getMessage());
		succeeded = false;
	}
	return succeeded;
}
 
Example 2
Project: Sem-Update   File: VentanaPrincipal.java   View Source Code Vote up 6 votes
private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed
    try {
        // Se intenta conectar, retorna IOException en caso que no pueda
        Socket socket = new Socket(servidor, numeroPuerto);

        // Stream para e/s, se crea primero la salida
        ObjectOutputStream salida = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream entrada = new ObjectInputStream(socket.getInputStream());

        salida.writeObject("Mata server" + id);
        jLabel1.setForeground(Color.red);

        entrada.close();
        salida.close();
        socket.close();
        url.setText("");
        jlabelSQL.setText("");
        this.setTitle("App [ID:?]");
    } catch (IOException ex) {
        System.out.println("(LOG) [ERROR] No se pudo contactar al servidor");
        Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 3
Project: r8   File: DexCallSite.java   View Source Code Vote up 6 votes
String build() {
  try {
    bytes = new ByteArrayOutputStream();
    out = new ObjectOutputStream(bytes);

    // We will generate SHA-1 hash of the call site information based on call site
    // attributes used in equality comparison, such that if the two call sites are
    // different their hashes should also be different.
    write(methodName);
    write(methodProto);
    write(bootstrapMethod);
    write(bootstrapArgs);
    out.close();

    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    digest.update(bytes.toByteArray());
    return BaseEncoding.base64Url().omitPadding().encode(digest.digest());
  } catch (NoSuchAlgorithmException | IOException ex) {
    throw new Unreachable("Cannot get SHA-1 message digest");
  }
}
 
Example 4
Project: RoughWorld   File: StoryInstance.java   View Source Code Vote up 6 votes
public static void saveObject(StoryInstance o,FileStoreInterface fs,String path)
	{
		try {
			fs.rename(path, "~"+path);
//			 File fout = new File(path);
//			 if(fout.exists())
//				 fout.delete();
	         FileOutputStream fileOut =
	         new FileOutputStream(path);
	         ObjectOutputStream out = new ObjectOutputStream(fileOut);
	         out.writeObject(o);
	         out.close();
	         fileOut.close();
	         
	         StateToXML.objectToXMLFile(o);
	      }
		catch(IOException i) 
	    {
	         i.printStackTrace();
	    }
	}
 
Example 5
Project: jaer   File: HumanVsComputerThrottleController.java   View Source Code Vote up 6 votes
synchronized public void doSaveThrottleSettings() {

        if (currentProfile == null) {
            log.warning("no profile to save");
            return;
        }
        try {

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(currentProfile.numPoints);
            oos.writeObject(currentProfile.throttleValues);
            putByteArray("throttleProfile", bos.toByteArray());
            oos.close();
            bos.close();
            log.info("throttle settings saveed to preferences");
            log.info("current throttle profile is "+currentProfile.toString());
        } catch (Exception e) {
            log.warning("couldn't save profile: " + e);
        }

    }
 
Example 6
Project: PearPlanner   File: StudyPlannerController.java   View Source Code Vote up 6 votes
/**
 * Save the current StudyPlanner into a serialized file.
 *
 * @param key64    SecretKey used for encoding.
 * @param fileName name of the file.
 * @return whether saved successfully.
 */
public boolean save(SecretKey key64, String fileName)
{
    try
    {
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, key64);
        SealedObject sealedObject = new SealedObject(this.planner, cipher);
        CipherOutputStream cipherOutputStream = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)), cipher);
        ObjectOutputStream outputStream = new ObjectOutputStream(cipherOutputStream);
        outputStream.writeObject(sealedObject);
        outputStream.close();
        return true;
    } catch (Exception e)
    {
        e.printStackTrace();
        return false;
    }
}
 
Example 7
Project: buildAPKsApps   File: SeismoDbAdapter.java   View Source Code Vote up 6 votes
public long createGraph(String name, ArrayList<ArrayList<Float>> graph) {
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  try {
    ObjectOutputStream objects = new ObjectOutputStream(bytes);
    objects.writeObject(graph);
    objects.close();
    bytes.close();
  } catch (IOException e) {
    // Do nothing.
  }

  ContentValues initial_values = new ContentValues();
  initial_values.put(KEY_TITLE, name);
  initial_values.put(KEY_BODY, bytes.toByteArray());

  return db_.insert(DATABASE_TABLE, null, initial_values);
}
 
Example 8
Project: LotusCloud   File: PacketClient.java   View Source Code Vote up 5 votes
public static Packet request(String host, int port, Packet packet) {
    KeyPair keyPair = Crypter.generateKeyPair();

    try {
        Socket socket = new Socket(host, port);

        if (socket.isClosed()) {
            return new ErrorPacket("socket closed");
        }

        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

        out.writeObject(keyPair.getPublic());
        PublicKey publicKey = (PublicKey) in.readObject();

        SecretKey key = Crypter.generateEC(keyPair.getPrivate(), publicKey);

        out.writeObject(Crypter.encrypt(key, Crypter.toByteArray(packet)));
        out.flush();

        Packet response = (Packet) Crypter.toObject(Crypter.decrypt(key, (byte[]) in.readObject()));

        in.close();
        out.close();
        socket.close();

        return response;
    } catch (Exception ex) {
        return new ErrorPacket(ex.getMessage());
    }
}
 
Example 9
Project: openjdk-jdk10   File: Correctness.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {

        String SIGALG = "SHA1withRSA";
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = kpg.generateKeyPair();

        SignedObject so1 = new SignedObject("Hello", kp.getPrivate(),
                Signature.getInstance(SIGALG));

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(so1);
        out.close();

        byte[] data = byteOut.toByteArray();

        SignedObject so2 = (SignedObject)new ObjectInputStream(
                new ByteArrayInputStream(data)).readObject();

        if (!so2.getObject().equals("Hello")) {
            throw new Exception("Content changed");
        }
        if (!so2.getAlgorithm().equals(SIGALG)) {
            throw new Exception("Signature algorithm unknown");
        }
        if (!so2.verify(kp.getPublic(), Signature.getInstance(SIGALG))) {
            throw new Exception("Not verified");
        }
    }
 
Example 10
Project: apfloat   File: ApintTest.java   View Source Code Vote up 5 votes
public static void testSerialization()
    throws IOException, ClassNotFoundException
{
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(buffer);
    Apint a = new Apint(5);
    out.writeObject(a);
    out.close();
    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
    Apint b = (Apint) in.readObject();
    assertEquals("5 equals", a, b);
    assertNotSame("5 !=", a, b);
}
 
Example 11
Project: BrainControl   File: StatisticalSummary.java   View Source Code Vote up 5 votes
public void save(String path) {
	try {
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
		oos.writeObject(this);
		oos.close();
	} catch (Exception e) {
		System.out.println(e);
	}
}
 
Example 12
Project: openjdk-jdk10   File: JSR166TestCase.java   View Source Code Vote up 5 votes
byte[] serialBytes(Object o) {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(o);
        oos.flush();
        oos.close();
        return bos.toByteArray();
    } catch (Throwable fail) {
        threadUnexpectedException(fail);
        return new byte[0];
    }
}
 
Example 13
Project: acs-demos   File: Player.java   View Source Code Vote up 5 votes
/**
 * Save the Player object so that we can load it dynamically at
 * application startup.
 * @throws IOException 
 */
public void save() throws IOException {
	 String filename = getName() + ".player";
	 FileOutputStream fileOut = new FileOutputStream(filename);
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(this);
         out.close();
         fileOut.close();
         logger.info("Serialized Player in `test_1.player`");
}
 
Example 14
Project: eps4j-core   File: EPSComm.java   View Source Code Vote up 5 votes
private static byte[] serialize(Serializable object) throws IOException {
    bos.reset();
    final ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(object);
    oos.flush();
    oos.close();
    bos.flush();
    return bos.toByteArray();
}
 
Example 15
Project: DIA-Umpire-Maven   File: LCMSPeakBase.java   View Source Code Vote up 5 votes
private void JavaSerializationPeakClusterWrite() {
    try {
        Logger.getRootLogger().info("Writing PeakCluster serialization to file:" + FilenameUtils.getBaseName(ScanCollectionName) + "_PeakCluster.ser...");
        FileOutputStream fout = new FileOutputStream(FilenameUtils.getFullPath(ParentmzXMLName) + FilenameUtils.getBaseName(ParentmzXMLName) + "_Peak/" + FilenameUtils.getBaseName(ScanCollectionName) + "_PeakCluster.ser", false);
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(PeakClusters);
        oos.close();
        fout.close();
    } catch (Exception ex) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(ex));
    }
}
 
Example 16
Project: lazycat   File: DeltaRequest.java   View Source Code Vote up 5 votes
/**
 * serialize DeltaRequest
 * 
 * @see DeltaRequest#writeExternal(java.io.ObjectOutput)
 * 
 * @return serialized delta request
 * @throws IOException
 */
protected byte[] serialize() throws IOException {
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(bos);
	writeExternal(oos);
	oos.flush();
	oos.close();
	return bos.toByteArray();
}
 
Example 17
Project: gamesboard   File: GameController.java   View Source Code Vote up 5 votes
public String getSerializedModel() {
	Memento memento = model.memento();
	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	try {
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
		objectOutputStream.writeObject(memento);
		objectOutputStream.close();
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
	return Base64.encodeToString(byteArrayOutputStream.toByteArray());
}
 
Example 18
Project: incubator-netbeans   File: ToolbarPoolTest.java   View Source Code Vote up 5 votes
private static Object writeInstance (final FileObject folder, final String name, final Object inst) throws IOException {
    class W implements FileSystem.AtomicAction {
        public Object create;
        
        public void run () throws IOException {
            FileObject fo = FileUtil.createData (folder, name);
            FileLock lock = fo.lock ();
            ObjectOutputStream oos = new ObjectOutputStream (fo.getOutputStream (lock));
            oos.writeObject (inst);
            oos.close ();
            lock.releaseLock ();
            
            DataObject obj = DataObject.find (fo);
            InstanceCookie ic = obj.getCookie(InstanceCookie.class);
            
            assertNotNull ("Cookie created", ic);
            try {
                create = ic.instanceCreate ();
                assertEquals ("The same instance class", inst.getClass(), create.getClass ());
            } catch (ClassNotFoundException ex) {
                fail (ex.getMessage ());
            }
        }
    }
    W w = new W ();
    folder.getFileSystem ().runAtomicAction (w);
    return w.create;
}
 
Example 19
Project: underlx   File: ExtraContentCache.java   View Source Code Vote up 5 votes
private void cacheConnectionInfo(String trivia, String stationId, String type, String locale) {
    CachedConnectionInfo toCache = new CachedConnectionInfo(trivia);
    try {
        FileOutputStream fos = new FileOutputStream(new File(context.getCacheDir(), String.format(CONN_INFO_CACHE_FILENAME, stationId, type, locale)));
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(toCache);
        os.close();
        fos.close();
    } catch (Exception e) {
        // oh well, we'll have to do without cache
        // caching is best-effort
        e.printStackTrace();
    }
}
 
Example 20
Project: lazycat   File: DeltaManager.java   View Source Code Vote up 5 votes
/**
 * serialize sessionID
 * 
 * @throws IOException
 *             if an input/output error occurs
 */
protected byte[] serializeSessionId(String sessionId) throws IOException {
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(bos);
	oos.writeUTF(sessionId);
	oos.flush();
	oos.close();
	return bos.toByteArray();
}