Example usage for java.io ObjectOutputStream writeUnshared

List of usage examples for java.io ObjectOutputStream writeUnshared

Introduction

In this page you can find the example usage for java.io ObjectOutputStream writeUnshared.

Prototype

public void writeUnshared(Object obj) throws IOException 

Source Link

Document

Writes an "unshared" object to the ObjectOutputStream.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    String s = "Hello World from java2s.com";

    FileOutputStream out = new FileOutputStream("test.txt");
    ObjectOutputStream oout = new ObjectOutputStream(out);

    // write something in the file
    oout.writeUnshared(s);
    oout.flush();// w  w w .  j  av a 2 s. com
    oout.close();
    // create an ObjectInputStream for the file we created before
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

    // read and print the unshared object
    System.out.println(ois.readUnshared());
    ois.close();
}

From source file:Person.java

public static void main(String[] args) throws Exception {
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("yourFile.dat"));

    Person person = new Person();
    person.setFirstName("A");
    person.setLastName("B");
    person.setAge(38);/*from   w  ww  .  ja v  a 2  s . c o m*/
    outputStream.writeObject(person);

    person = new Person();
    person.setFirstName("C");
    person.setLastName("D");
    person.setAge(22);

    outputStream.writeUnshared(person);

    outputStream.close();
}

From source file:org.qi4j.runtime.types.SerializableType.java

public Object toJSON(Object value) throws JSONException {
    // Check if we are serializing an Entity
    if (value instanceof EntityComposite) {
        // Store reference instead
        value = EntityReference.getEntityReference(value);
    } else if (value instanceof ValueComposite) {
        // Serialize ValueComposite JSON instead
        CompositeInstance instance = (CompositeInstance) Proxy.getInvocationHandler(value);
        ValueDescriptor descriptor = (ValueDescriptor) instance.descriptor();
        ValueType valueType = descriptor.valueType();
        try {/*from w w  w.  j a v  a 2 s  .  c  om*/
            JSONObject object = (JSONObject) valueType.toJSON(value);
            object.put("_type", descriptor.type().getName());
            return object;
        } catch (JSONException e) {
            throw new IllegalStateException("Could not JSON serialize value", e);
        }
    }

    // Serialize value
    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeUnshared(value);
        out.close();
        byte[] bytes = Base64Encoder.encode(bout.toByteArray(), true);
        String stringValue = new String(bytes, "UTF-8");
        return stringValue;
    } catch (IOException e) {
        throw new IllegalArgumentException("Could not serialize value", e);
    }
}

From source file:de.dal33t.powerfolder.util.ByteSerializer.java

/**
 * Serialize an object. This method is non-static an re-uses the internal
 * byteoutputstream/*from  ww w . j  av  a  2 s  . co  m*/
 *
 * @param target
 *            The object to be serialized
 * @param compress
 *            true if serialization should compress.
 * @param padToSize
 *            the size to pad the output buffer to. number below 0 means no
 *            padding.
 * @return The serialized object
 * @throws IOException
 *             In case the object cannot be serialized
 */
public byte[] serialize(Serializable target, boolean compress, int padToSize) throws IOException {
    long start = System.currentTimeMillis();
    ByteArrayOutputStream byteOut;
    // Reset buffer
    if (outBufferRef != null && outBufferRef.get() != null) {
        // Reuse old buffer
        byteOut = outBufferRef.get();
        byteOut.reset();
    } else {
        // logFiner("Creating send buffer (512bytes)");
        // Create new bytearray output, 512b buffer
        byteOut = new ByteArrayOutputStream(512);
        if (CACHE_OUT_BUFFER) {
            // Chache outgoing buffer
            outBufferRef = new SoftReference<ByteArrayOutputStream>(byteOut);
        }
    }

    OutputStream targetOut;
    // Serialize....
    if (compress) {
        PFZIPOutputStream zipOut = new PFZIPOutputStream(byteOut);
        targetOut = zipOut;
    } else {
        targetOut = byteOut;
    }
    ObjectOutputStream objOut = new ObjectOutputStream(targetOut);

    // Write
    try {
        objOut.writeUnshared(target);
    } catch (StreamCorruptedException e) {
        LOG.log(Level.WARNING, "Problem while serializing: " + e, e);
        throw e;
    } catch (InvalidClassException e) {
        LOG.log(Level.WARNING, "Problem while serializing: " + target + ": " + e, e);
        throw e;
    }

    objOut.close();

    if (padToSize > 0) {
        int modulo = byteOut.size() % padToSize;
        if (modulo != 0) {
            int additionalBytesRequired = padToSize - (modulo);
            // LOG.warn("Buffersize: " + byteOut.size()
            // + ", Additonal bytes required: " + additionalBytesRequired);
            for (int i = 0; i < additionalBytesRequired; i++) {
                byteOut.write(0);
            }
        }
    }
    byteOut.flush();
    byteOut.close();

    if (byteOut.size() >= 256 * 1024) {
        logWarning("Send buffer exceeds 256KB! " + Format.formatBytes(byteOut.size()) + ". Message: " + target);
    }

    byte[] buf = byteOut.toByteArray();
    if (BENCHMARK) {
        totalObjects++;
        totalTime += System.currentTimeMillis() - start;
        int count = 0;
        if (CLASS_STATS.containsKey(target.getClass())) {
            count = CLASS_STATS.get(target.getClass());
        }
        count++;
        CLASS_STATS.put(target.getClass(), count);
    }
    return buf;
}