Java Code Examples for java.io.ObjectOutputStream

The following are top voted examples for showing how to use java.io.ObjectOutputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: NulFile.java   View source code 7 votes vote down vote up
private static void testSerialization(File testFile) {
    String path = testFile.getPath();
    try {
        // serialize test file
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(testFile);
        oos.close();
        // deserialize test file
        byte[] bytes = baos.toByteArray();
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(is);
        File newFile = (File) ois.readObject();
        // test
        String newPath = newFile.getPath();
        if (!path.equals(newPath)) {
            throw new RuntimeException(
                    "Serialization should not change file path");
        }
        test(newFile, false);
    } catch (IOException | ClassNotFoundException ex) {
        System.err.println("Exception happens in testSerialization");
        System.err.println(ex.getMessage());
    }
}
 
Example 2
Project: openjdk-jdk10   File: ModelMBeanConstructorInfo.java   View source code 6 votes vote down vote up
/**
 * Serializes a {@link ModelMBeanConstructorInfo} to an {@link ObjectOutputStream}.
 */
private void writeObject(ObjectOutputStream out)
        throws IOException {
  if (compat)
  {
    // Serializes this instance in the old serial form
    //
    ObjectOutputStream.PutField fields = out.putFields();
    fields.put("consDescriptor", consDescriptor);
    fields.put("currClass", currClass);
    out.writeFields();
  }
  else
  {
    // Serializes this instance in the new serial form
    //
    out.defaultWriteObject();
  }
}
 
Example 3
Project: PicShow-zhaipin   File: DataHelper.java   View source code 6 votes vote down vote up
/**
 * 将对象储存到sharepreference
 *
 * @param key
 * @param device
 * @param <T>
 */
public static <T> boolean saveDeviceData(Context context, String key, T device) {
    if (mSharedPreferences == null) {
        mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {   //Device为自定义类
        // 创建对象输出流,并封装字节流
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        // 将对象写入字节流
        oos.writeObject(device);
        // 将字节流编码成base64的字符串
        String oAuth_Base64 = new String(Base64.encode(baos
                .toByteArray(), Base64.DEFAULT));
        mSharedPreferences.edit().putString(key, oAuth_Base64).commit();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 4
Project: jdk8u-jdk   File: LongArrays.java   View source code 6 votes vote down vote up
/**
 * Write and read long arrays to/from a stream.  The benchmark is run in
 * batches, with each batch consisting of a fixed number of read/write
 * cycles.  The ObjectOutputStream is reset after each batch of cycles has
 * completed.
 * Arguments: <array size> <# batches> <# cycles per batch>
 */
public long run(String[] args) throws Exception {
    int size = Integer.parseInt(args[0]);
    int nbatches = Integer.parseInt(args[1]);
    int ncycles = Integer.parseInt(args[2]);
    long[][] arrays = new long[ncycles][size];
    StreamBuffer sbuf = new StreamBuffer();
    ObjectOutputStream oout =
        new ObjectOutputStream(sbuf.getOutputStream());
    ObjectInputStream oin =
        new ObjectInputStream(sbuf.getInputStream());

    doReps(oout, oin, sbuf, arrays, 1);     // warmup

    long start = System.currentTimeMillis();
    doReps(oout, oin, sbuf, arrays, nbatches);
    return System.currentTimeMillis() - start;
}
 
Example 5
Project: jdk8u-jdk   File: SerializationDeadlock.java   View source code 6 votes vote down vote up
public void run() {
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final ObjectOutputStream oos = new ObjectOutputStream(baos);

        oos.writeObject(vector);
        oos.close();
    } catch (final IOException ioe) {
        addException(ioe);
    } finally {
        try {
            testEnd.await();
        } catch (Exception e) {
            addException(e);
        }
    }
}
 
Example 6
Project: jdk8u-jdk   File: CertificateRevokedException.java   View source code 6 votes vote down vote up
/**
 * Serialize this {@code CertificateRevokedException} instance.
 *
 * @serialData the size of the extensions map (int), followed by all of
 * the extensions in the map, in no particular order. For each extension,
 * the following data is emitted: the OID String (Object), the criticality
 * flag (boolean), the length of the encoded extension value byte array
 * (int), and the encoded extension value bytes.
 */
private void writeObject(ObjectOutputStream oos) throws IOException {
    // Write out the non-transient fields
    // (revocationDate, reason, authority)
    oos.defaultWriteObject();

    // Write out the size (number of mappings) of the extensions map
    oos.writeInt(extensions.size());

    // For each extension in the map, the following are emitted (in order):
    // the OID String (Object), the criticality flag (boolean), the length
    // of the encoded extension value byte array (int), and the encoded
    // extension value byte array. The extensions themselves are emitted
    // in no particular order.
    for (Map.Entry<String, Extension> entry : extensions.entrySet()) {
        Extension ext = entry.getValue();
        oos.writeObject(ext.getId());
        oos.writeBoolean(ext.isCritical());
        byte[] extVal = ext.getValue();
        oos.writeInt(extVal.length);
        oos.write(extVal);
    }
}
 
Example 7
Project: NotifyTools   File: BeanContextSupport.java   View source code 6 votes vote down vote up
/**
 * Serializes the given collection.
 * <p>
 * First writes a <code>int</code> indicating the number of all 
 * serializable elements (implements <code>Serializable</code>, then
 * objects are writtern one by one.</p>
 * 
 * @param oos           the stream where the collection is writtern to
 * @param collection    the collection to serialize
 * @throws IOException if I/O exception occurs
 */
protected final void serialize(ObjectOutputStream oos, Collection collection)
        throws IOException {
    Object array[] = collection.toArray();
    int serCount = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] instanceof Serializable) {
            serCount++;
        }
    }

    oos.writeInt(serCount);
    for (int i = 0; i < array.length; i++) {
        if (array[i] instanceof Serializable) {
            oos.writeObject(array[i]);
        }
    }
}
 
Example 8
Project: alfresco-core   File: SerializableTypeHandler.java   View source code 6 votes vote down vote up
public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
{
    if (parameter == null)
    {
        ps.setNull(i, SerializableTypeHandler.serializableType);
    }
    else
    {
        try
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(parameter);
            byte[] bytes = baos.toByteArray();
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ps.setBinaryStream(i, bais, bytes.length);
        }
        catch (Throwable e)
        {
            throw new SerializationException(e);
        }
    }
}
 
Example 9
Project: OpenJSharp   File: JPopupMenu.java   View source code 6 votes vote down vote up
private void writeObject(ObjectOutputStream s) throws IOException {
    Vector<Object> values = new Vector<Object>();

    s.defaultWriteObject();
    // Save the invoker, if its Serializable.
    if(invoker != null && invoker instanceof Serializable) {
        values.addElement("invoker");
        values.addElement(invoker);
    }
    // Save the popup, if its Serializable.
    if(popup != null && popup instanceof Serializable) {
        values.addElement("popup");
        values.addElement(popup);
    }
    s.writeObject(values);

    if (getUIClassID().equals(uiClassID)) {
        byte count = JComponent.getWriteObjCounter(this);
        JComponent.setWriteObjCounter(this, --count);
        if (count == 0 && ui != null) {
            ui.installUI(this);
        }
    }
}
 
Example 10
Project: GitHub   File: DataHelper.java   View source code 6 votes vote down vote up
/**
 * 将对象储存到sharepreference
 *
 * @param key
 * @param device
 * @param <T>
 */
public static <T> boolean saveDeviceData(Context context, String key, T device) {
    if (mSharedPreferences == null) {
        mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {   //Device为自定义类
        // 创建对象输出流,并封装字节流
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        // 将对象写入字节流
        oos.writeObject(device);
        // 将字节流编码成base64的字符串
        String oAuth_Base64 = new String(Base64.encode(baos
                .toByteArray(), Base64.DEFAULT));
        mSharedPreferences.edit().putString(key, oAuth_Base64).commit();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 11
Project: openjdk-jdk10   File: ModelMBeanAttributeInfo.java   View source code 6 votes vote down vote up
/**
 * Serializes a {@link ModelMBeanAttributeInfo} to an {@link ObjectOutputStream}.
 */
private void writeObject(ObjectOutputStream out)
        throws IOException {
  if (compat)
  {
    // Serializes this instance in the old serial form
    //
    ObjectOutputStream.PutField fields = out.putFields();
    fields.put("attrDescriptor", attrDescriptor);
    fields.put("currClass", currClass);
    out.writeFields();
  }
  else
  {
    // Serializes this instance in the new serial form
    //
    out.defaultWriteObject();
  }
}
 
Example 12
Project: directory-ldap-api   File: AvaSerializationTest.java   View source code 6 votes vote down vote up
@Test
public void testNullUpValueStaticSerialization() throws LdapException, IOException, ClassNotFoundException
{
    Ava atav = new Ava( schemaManager, "DC", ( String ) null );

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream( baos );

    try
    {
        atav.writeExternal( out );
        fail();
    }
    catch ( IOException ioe )
    {
        String message = ioe.getMessage();
        assertEquals( "Cannot serialize a wrong ATAV, the value should not be null", message );
    }
}
 
Example 13
Project: directory-ldap-api   File: AvaSerializationTest.java   View source code 6 votes vote down vote up
/**
 * Test serialization of a simple ATAV
 */
@Test
public void testNullAtavSerialization() throws LdapException, IOException, ClassNotFoundException
{
    Ava atav = new Ava();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream( baos );

    try
    {
        atav.writeExternal( out );
        fail();
    }
    catch ( IOException ioe )
    {
        assertTrue( true );
    }
}
 
Example 14
Project: datatree   File: TreeTest.java   View source code 6 votes vote down vote up
private final void testSerializationAndCloning(Tree node) throws Exception {

		// Serialize
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(node);
		oos.flush();
		byte[] bytes = baos.toByteArray();
		// System.out.println(new String(bytes));

		// Deserialize
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = new ObjectInputStream(bais);
		Tree copy = (Tree) ois.readObject();

		String txtOriginal = node.toString("debug");
		String txtCopy = copy.toString("debug");

		assertEquals(txtOriginal, txtCopy);

		// Cloning
		txtCopy = node.clone().toString("debug");
		assertEquals(txtOriginal, txtCopy);
	}
 
Example 15
Project: parabuild-ci   File: DialValueIndicatorTests.java   View source code 6 votes vote down vote up
/**
 * Serialize an instance, restore it, and check for equality.
 */
public void testSerialization() {
    // test a default instance
    DialValueIndicator i1 = new DialValueIndicator(0, "Label");
    DialValueIndicator i2 = null;

    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(i1);
        out.close();

        ObjectInput in = new ObjectInputStream(
                new ByteArrayInputStream(buffer.toByteArray()));
        i2 = (DialValueIndicator) in.readObject();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(i1, i2);
    
    // test a custom instance
}
 
Example 16
Project: android_Json2view   File: XViewBody.java   View source code 6 votes vote down vote up
public XViewBody deepClone() {


        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(this);
            ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(bi);
            Object o = oi.readObject();
            oi.close();
            bi.close();
            return (XViewBody) o;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }
 
Example 17
Project: 360w17g1   File: AbstractController.java   View source code 6 votes vote down vote up
/**
 * 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 18
Project: jdk8u-jdk   File: BigInteger.java   View source code 6 votes vote down vote up
/**
     * Save the {@code BigInteger} instance to a stream.
     * The magnitude of a BigInteger is serialized as a byte array for
     * historical reasons.
     *
     * @serialData two necessary fields are written as well as obsolete
     *             fields for compatibility with older versions.
     */
    private void writeObject(ObjectOutputStream s) throws IOException {
        // set the values of the Serializable fields
        ObjectOutputStream.PutField fields = s.putFields();
        fields.put("signum", signum);
        fields.put("magnitude", magSerializedForm());
        // The values written for cached fields are compatible with older
        // versions, but are ignored in readObject so don't otherwise matter.
        fields.put("bitCount", -1);
        fields.put("bitLength", -1);
        fields.put("lowestSetBit", -2);
        fields.put("firstNonzeroByteNum", -2);

        // save them
        s.writeFields();
}
 
Example 19
Project: openjdk-jdk10   File: BeanContextSupport.java   View source code 6 votes vote down vote up
/**
 * Used by writeObject to serialize a Collection.
 * @param oos the {@code ObjectOutputStream}
 * to use during serialization
 * @param coll the {@code Collection} to serialize
 * @throws IOException if serialization failed
 */
protected final void serialize(ObjectOutputStream oos, Collection<?> coll) throws IOException {
    int      count   = 0;
    Object[] objects = coll.toArray();

    for (int i = 0; i < objects.length; i++) {
        if (objects[i] instanceof Serializable)
            count++;
        else
            objects[i] = null;
    }

    oos.writeInt(count); // number of subsequent objects

    for (int i = 0; count > 0; i++) {
        Object o = objects[i];

        if (o != null) {
            oos.writeObject(o);
            count--;
        }
    }
}
 
Example 20
Project: openjdk-jdk10   File: IntArrays.java   View source code 6 votes vote down vote up
/**
 * Write and read int arrays to/from a stream.  The benchmark is run in
 * batches, with each batch consisting of a fixed number of read/write
 * cycles.  The ObjectOutputStream is reset after each batch of cycles has
 * completed.
 * Arguments: <array size> <# batches> <# cycles per batch>
 */
public long run(String[] args) throws Exception {
    int size = Integer.parseInt(args[0]);
    int nbatches = Integer.parseInt(args[1]);
    int ncycles = Integer.parseInt(args[2]);
    int[][] arrays = new int[ncycles][size];
    StreamBuffer sbuf = new StreamBuffer();
    ObjectOutputStream oout =
        new ObjectOutputStream(sbuf.getOutputStream());
    ObjectInputStream oin =
        new ObjectInputStream(sbuf.getInputStream());

    doReps(oout, oin, sbuf, arrays, 1);     // warmup

    long start = System.currentTimeMillis();
    doReps(oout, oin, sbuf, arrays, nbatches);
    return System.currentTimeMillis() - start;
}
 
Example 21
Project: OpenJSharp   File: SocketPermission.java   View source code 6 votes vote down vote up
/**
 * @serialData "permissions" field (a Vector containing the SocketPermissions).
 */
/*
 * Writes the contents of the perms field out as a Vector for
 * serialization compatibility with earlier releases.
 */
private void writeObject(ObjectOutputStream out) throws IOException {
    // Don't call out.defaultWriteObject()

    // Write out Vector
    Vector<SocketPermission> permissions = new Vector<>(perms.size());

    synchronized (this) {
        permissions.addAll(perms);
    }

    ObjectOutputStream.PutField pfields = out.putFields();
    pfields.put("permissions", permissions);
    out.writeFields();
}
 
Example 22
Project: EatDubbo   File: TelnetCodecTest.java   View source code 6 votes vote down vote up
protected byte[] objectToByte(Object obj){
    byte[] bytes; 
    if (obj instanceof String){
        bytes = ((String)obj).getBytes();
    } else if (obj instanceof byte[]){
        bytes = (byte[]) obj;
    } else {
        try { 
            //object to bytearray 
            ByteArrayOutputStream bo = new ByteArrayOutputStream(); 
            ObjectOutputStream oo = new ObjectOutputStream(bo); 
            oo.writeObject(obj); 
            bytes = bo.toByteArray(); 
            bo.close(); 
            oo.close();     
        } 
        catch(Exception e){ 
            throw new RuntimeException(e);
        } 
    }
    return(bytes); 
}
 
Example 23
Project: OpenJSharp   File: RoleUnresolved.java   View source code 6 votes vote down vote up
/**
 * Serializes a {@link RoleUnresolved} to an {@link ObjectOutputStream}.
 */
private void writeObject(ObjectOutputStream out)
        throws IOException {
  if (compat)
  {
    // Serializes this instance in the old serial form
    //
    ObjectOutputStream.PutField fields = out.putFields();
    fields.put("myRoleName", roleName);
    fields.put("myRoleValue", roleValue);
    fields.put("myPbType", problemType);
    out.writeFields();
  }
  else
  {
    // Serializes this instance in the new serial form
    //
    out.defaultWriteObject();
  }
}
 
Example 24
Project: jdk8u-jdk   File: RoleInfo.java   View source code 6 votes vote down vote up
/**
 * Serializes a {@link RoleInfo} to an {@link ObjectOutputStream}.
 */
private void writeObject(ObjectOutputStream out)
        throws IOException {
  if (compat)
  {
    // Serializes this instance in the old serial form
    //
    ObjectOutputStream.PutField fields = out.putFields();
    fields.put("myName", name);
    fields.put("myIsReadableFlg", isReadable);
    fields.put("myIsWritableFlg", isWritable);
    fields.put("myDescription", description);
    fields.put("myMinDegree", minDegree);
    fields.put("myMaxDegree", maxDegree);
    fields.put("myRefMBeanClassName", referencedMBeanClassName);
    out.writeFields();
  }
  else
  {
    // Serializes this instance in the new serial form
    //
    out.defaultWriteObject();
  }
}
 
Example 25
Project: incubator-netbeans   File: XMLMapAttr.java   View source code 6 votes vote down vote up
/**
 * Encodes Object into String encoded in HEX format
 * @param value Object, which will be encoded
 * @return  serialized Object in String encoded in HEX format
 * @throws IOException
 */
static String encodeValue(Object value) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(value);
        oos.close();
    } catch (Exception e) {
        throw (IOException) ExternalUtil.copyAnnotation(new IOException(), e);
    }

    byte[] bArray = bos.toByteArray();
    StringBuffer strBuff = new StringBuffer(bArray.length * 2);

    for (int i = 0; i < bArray.length; i++) {
        if ((bArray[i] < 16) && (bArray[i] >= 0)) {
            strBuff.append("0"); // NOI18N
        }

        strBuff.append(Integer.toHexString((bArray[i] < 0) ? (bArray[i] + 256) : bArray[i]));
    }

    return strBuff.toString();
}
 
Example 26
Project: incubator-netbeans   File: PriorityListenerList.java   View source code 6 votes vote down vote up
private void writeObject(ObjectOutputStream s) throws IOException {
    s.defaultWriteObject();
    
    // Save serializable event listeners
    int priority = listenersArray.length - 1; // max priority
    s.writeInt(priority); // write max priority
    for (; priority >= 0; priority--) {
        T[] listeners = listenersArray[priority];
        // Write in opposite order of adding 
        for (int i = 0; i < listeners.length; i++) {
            T listener = listeners[i];
            // Save only the serializable listeners
            if (listener instanceof Serializable) {
                s.writeObject(listener);
            }
        }
        s.writeObject(null);
    }
}
 
Example 27
Project: DigitRecognizer   File: Serializer.java   View source code 6 votes vote down vote up
public static byte[] serialize(Serializable obj)
{
    try
    {
        try(ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream objStream = new ObjectOutputStream(out);)
        {
            objStream.writeObject(obj);
            return out.toByteArray();
        }
    }
    catch(Exception ex)
    {
        throw new RuntimeException("Failed to serialize Object of type "
                                   + (obj == null ? "null" : obj.getClass().getName()), ex);
    }
}
 
Example 28
Project: incubator-netbeans   File: CommonWireIOTestCase.java   View source code 6 votes vote down vote up
public WireIO createWireIOClient(Socket clientSocket) {
    try {
        clientSocket.setSoTimeout(0);
        clientSocket.setTcpNoDelay(true); // Necessary at least on Solaris to avoid delays in e.g. readInt() etc.

        ObjectOutputStream socketOut = new ObjectOutputStream(clientSocket.getOutputStream());
        ObjectInputStream socketIn = new ObjectInputStream(clientSocket.getInputStream());
        WireIO wireIO = new WireIO(socketOut, socketIn);

        return wireIO;
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return null;
}
 
Example 29
Project: sstore-soft   File: LinkedHashMultimap.java   View source code 5 votes vote down vote up
/**
 * @serialData the expected values per key, the number of distinct keys,
 * the number of entries, and the entries in order
 */
@GwtIncompatible("java.io.ObjectOutputStream")
private void writeObject(ObjectOutputStream stream) throws IOException {
  stream.defaultWriteObject();
  stream.writeInt(valueSetCapacity);
  stream.writeInt(keySet().size());
  for (K key : keySet()) {
    stream.writeObject(key);
  }
  stream.writeInt(size());
  for (Map.Entry<K, V> entry : entries()) {
    stream.writeObject(entry.getKey());
    stream.writeObject(entry.getValue());
  }
}
 
Example 30
Project: openjdk-systemtest   File: TestLambdaSerialization.java   View source code 5 votes vote down vote up
private byte[] writeObject(Object object) throws IOException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
       ObjectOutput out = new ObjectOutputStream(baos);
	out.writeObject(object);
       out.close();
	return baos.toByteArray();
}
 
Example 31
Project: lazycat   File: XByteBuffer.java   View source code 5 votes vote down vote up
/**
 * Serializes a message into cluster data
 * 
 * @param msg
 *            ClusterMessage
 * @return serialized content as byte[] array
 * @throws IOException
 */
public static byte[] serialize(Serializable msg) throws IOException {
	ByteArrayOutputStream outs = new ByteArrayOutputStream();
	ObjectOutputStream out = new ObjectOutputStream(outs);
	out.writeObject(msg);
	out.flush();
	byte[] data = outs.toByteArray();
	return data;
}
 
Example 32
Project: imagingbook-common   File: SerializationHelper.java   View source code 5 votes vote down vote up
/**
 * Writes a serialized representation of an arbitrary Java object to 
 * a file. Make sure the serialized object is composed of standard Java types 
 * only to avoid class loader problems.
 *  
 * @param any The object to be serialized.
 * @param fileName The file to write to.
 * @return The full path of the written file.
 */
public static String writeObject(Object any, String fileName) {
	File file = new File(fileName);
	String path = file.getAbsolutePath();
	try (FileOutputStream strm = new FileOutputStream(file);
		 OutputStream buffer = new BufferedOutputStream(strm);
		 ObjectOutput output = new ObjectOutputStream(buffer);) 
	{
		output.writeObject(any);
	} catch (IOException e) {
		System.err.println("Output error.");
		return null;
	}
	return path;
}
 
Example 33
Project: ipack   File: JCEElGamalPublicKey.java   View source code 5 votes vote down vote up
private void writeObject(
    ObjectOutputStream  out)
    throws IOException
{
    out.writeObject(this.getY());
    out.writeObject(elSpec.getP());
    out.writeObject(elSpec.getG());
}
 
Example 34
Project: openjdk-jdk10   File: BaseTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> T serializeDeserializeObject(T o)
        throws IOException, ClassNotFoundException {
    T o1;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
        oos.writeObject(o);
    }
    try (ObjectInputStream ois
            = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
        o1 = (T) ois.readObject();
    }
    return o1;
}
 
Example 35
Project: jdk8u-jdk   File: XPathExceptionInitCause.java   View source code 5 votes vote down vote up
static byte [] pickleXPE(XPathException xpe) throws IOException {
    ByteArrayOutputStream bos =  new ByteArrayOutputStream();
    ObjectOutputStream xpeos = new ObjectOutputStream(bos);
    xpeos.writeObject(xpe);
    xpeos.close();
    return bos.toByteArray();
}
 
Example 36
Project: incubator-ratis   File: ProtoUtils.java   View source code 5 votes vote down vote up
static ByteString writeObject2ByteString(Object obj) {
  final ByteString.Output byteOut = ByteString.newOutput();
  try(final ObjectOutputStream objOut = new ObjectOutputStream(byteOut)) {
    objOut.writeObject(obj);
  } catch (IOException e) {
    throw new IllegalStateException(
        "Unexpected IOException when writing an object to a ByteString.", e);
  }
  return byteOut.toByteString();
}
 
Example 37
Project: FuzzDroid   File: SocketServer.java   View source code 5 votes vote down vote up
private void sendResponse(ObjectOutputStream out, Object response)
		throws IOException {
	out.writeObject(response);
	out.flush();
	System.out.println("sending response to client-app...");
	System.out.println(response);
}
 
Example 38
Project: SmartChart   File: SerializableCookie.java   View source code 5 votes vote down vote up
private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeObject(cookie.name());
    out.writeObject(cookie.value());
    out.writeLong(cookie.persistent() ? cookie.expiresAt() : NON_VALID_EXPIRES_AT);
    out.writeObject(cookie.domain());
    out.writeObject(cookie.path());
    out.writeBoolean(cookie.secure());
    out.writeBoolean(cookie.httpOnly());
    out.writeBoolean(cookie.hostOnly());
}
 
Example 39
Project: OpenJSharp   File: JTabbedPane.java   View source code 5 votes vote down vote up
/**
 * See <code>readObject</code> and <code>writeObject</code> in
 * <code>JComponent</code> for more
 * information about serialization in Swing.
 */
private void writeObject(ObjectOutputStream s) throws IOException {
    s.defaultWriteObject();
    if (getUIClassID().equals(uiClassID)) {
        byte count = JComponent.getWriteObjCounter(this);
        JComponent.setWriteObjCounter(this, --count);
        if (count == 0 && ui != null) {
            ui.installUI(this);
        }
    }
}
 
Example 40
Project: parabuild-ci   File: ValueAxis.java   View source code 5 votes vote down vote up
/**
 * Provides serialization support.
 *
 * @param stream  the output stream.
 *
 * @throws IOException  if there is an I/O error.
 */
private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.defaultWriteObject();
    SerialUtilities.writeShape(this.upArrow, stream);
    SerialUtilities.writeShape(this.downArrow, stream);
    SerialUtilities.writeShape(this.leftArrow, stream);
    SerialUtilities.writeShape(this.rightArrow, stream);
}