Example usage for java.io ObjectOutputStream writeByte

List of usage examples for java.io ObjectOutputStream writeByte

Introduction

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

Prototype

public void writeByte(int val) throws IOException 

Source Link

Document

Writes an 8 bit byte.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    byte b = 127;

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

    // write something in the file
    oout.writeByte(b);
    oout.flush();/*w w  w.  j  a  v  a  2  s  .  co  m*/
    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.readUnsignedByte());
    ois.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    byte b = 12;/*from   w  w  w  .  j  ava 2  s  .  c om*/

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

    // write something in the file
    oout.writeByte(b);
    oout.writeByte(21);
    oout.flush();
    oout.close();
    // create an ObjectInputStream for the file we created before
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

    // read and print a byte
    System.out.println((char) ois.readByte());

    // read and print a byte
    System.out.println((char) ois.readByte());
    ois.close();

}

From source file:Main.java

public static void main(String[] args) throws Exception {

    ObjectOutputStream out = new ObjectOutputStream(
            new BufferedOutputStream(new FileOutputStream("file.data")));
    out.writeByte(1);
    out.close();/*  w  w w . j a va2s  . c  o  m*/

    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("file.data")));

    byte[] byteArray = new byte[10];
    in.read(byteArray);
    System.out.println(Arrays.toString(byteArray));
    in.close();
}

From source file:jfs.sync.encryption.JFSEncryptedStream.java

public static OutputStream createOutputStream(long compressionLimit, OutputStream baseOutputStream, long length,
        Cipher cipher) throws IOException {
    OutputStream result = null;//w w  w. ja  v  a2  s . c  o  m
    Runtime runtime = Runtime.getRuntime();
    long freeMem = runtime.totalMemory() / SPACE_RESERVE;
    if (length >= freeMem) {
        if (log.isWarnEnabled()) {
            log.warn("JFSEncryptedStream.createOutputStream() GC " + freeMem + "/" + runtime.maxMemory());
        } // if
        runtime.gc();
        freeMem = runtime.totalMemory() / SPACE_RESERVE;
    } // if
    if ((length < compressionLimit) && (length < freeMem)) {
        result = new JFSEncryptedStream(baseOutputStream, cipher);
    } else {
        if (length < freeMem) {
            if (log.isInfoEnabled()) {
                log.info("JFSEncryptedStream.createOutputStream() not compressing");
            } // if
        } else {
            if (log.isWarnEnabled()) {
                log.warn("JFSEncryptedStream.createOutputStream() due to memory constraints (" + length + "/"
                        + freeMem + ") not compressing");
            } // if
        } // if
        ObjectOutputStream oos = new ObjectOutputStream(baseOutputStream);
        oos.writeByte(COMPRESSION_NONE);
        oos.writeLong(length);
        oos.flush();
        result = baseOutputStream;
        if (cipher != null) {
            result = new CipherOutputStream(result, cipher);
        } // if
    } // if
    return result;
}

From source file:ByteArrayList.java

private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();/*from   ww w .ja v a2  s . c  o  m*/
    out.writeInt(array.length);
    for (int i = 0; i < size; i++) {
        out.writeByte(array[i]);
    }
}

From source file:jfs.sync.encryption.JFSEncryptedStream.java

private void internalClose() throws IOException {
    delegate.close();/*from  w w  w .  j  a  v  a2 s . c  om*/
    byte[] bytes = delegate.toByteArray();
    final byte[] originalBytes = bytes;
    long l = bytes.length;

    byte marker = COMPRESSION_NONE;

    if (log.isDebugEnabled()) {
        log.debug("close() checking for compressions for");
    } // if

    CompressionThread dt = new CompressionThread(originalBytes) {

        @Override
        public void run() {
            try {
                ByteArrayOutputStream deflaterStream = new ByteArrayOutputStream();
                Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true);
                OutputStream dos = new DeflaterOutputStream(deflaterStream, deflater, COMPRESSION_BUFFER_SIZE);
                dos.write(originalBytes);
                dos.close();
                compressedValue = deflaterStream.toByteArray();
            } catch (Exception e) {
                log.error("run()", e);
            } // try/catch
        } // run()

    };

    CompressionThread bt = new CompressionThread(originalBytes) {

        @Override
        public void run() {
            try {
                if (originalBytes.length > BZIP_MAX_LENGTH) {
                    compressedValue = originalBytes;
                } else {
                    ByteArrayOutputStream bzipStream = new ByteArrayOutputStream();
                    OutputStream bos = new BZip2CompressorOutputStream(bzipStream);
                    bos.write(originalBytes);
                    bos.close();
                    compressedValue = bzipStream.toByteArray();
                } // if
            } catch (Exception e) {
                log.error("run()", e);
            } // try/catch
        } // run()

    };

    CompressionThread lt = new CompressionThread(originalBytes) {

        /*
         * // "  -a{N}:  set compression mode - [0, 1], default: 1 (max)\n" +
         * "  -d{N}:  set dictionary - [0,28], default: 23 (8MB)\n"
         * +"  -fb{N}: set number of fast bytes - [5, 273], default: 128\n"
         * +"  -lc{N}: set number of literal context bits - [0, 8], default: 3\n"
         * +"  -lp{N}: set number of literal pos bits - [0, 4], default: 0\n"
         * +"  -pb{N}: set number of pos bits - [0, 4], default: 2\n"
         * +"  -mf{MF_ID}: set Match Finder: [bt2, bt4], default: bt4\n"+"  -eos:   write End Of Stream marker\n");
         */
        private int dictionarySize = 1 << 23;

        private int lc = 3;

        private int lp = 0;

        private int pb = 2;

        private int fb = 128;

        public int algorithm = 2;

        public int matchFinderIndex = 1; // 0, 1, 2

        @Override
        public void run() {
            try {
                Encoder encoder = new Encoder();
                encoder.SetEndMarkerMode(false);
                encoder.SetAlgorithm(algorithm); // Whatever that means
                encoder.SetDictionarySize(dictionarySize);
                encoder.SetNumFastBytes(fb);
                encoder.SetMatchFinder(matchFinderIndex);
                encoder.SetLcLpPb(lc, lp, pb);

                ByteArrayOutputStream lzmaStream = new ByteArrayOutputStream();
                ByteArrayInputStream inStream = new ByteArrayInputStream(originalBytes);

                encoder.WriteCoderProperties(lzmaStream);
                encoder.Code(inStream, lzmaStream, -1, -1, null);
                compressedValue = lzmaStream.toByteArray();
            } catch (Exception e) {
                log.error("run()", e);
            } // try/catch
        } // run()

    };

    dt.start();
    bt.start();
    lt.start();

    try {
        dt.join();
        bt.join();
        lt.join();
    } catch (InterruptedException e) {
        log.error("run()", e);
    } // try/catch

    if (dt.compressedValue.length < l) {
        marker = COMPRESSION_DEFLATE;
        bytes = dt.compressedValue;
        l = bytes.length;
    } // if

    if (lt.compressedValue.length < l) {
        marker = COMPRESSION_LZMA;
        bytes = lt.compressedValue;
        l = bytes.length;
    } // if

    if (bt.compressedValue.length < l) {
        marker = COMPRESSION_BZIP2;
        bytes = bt.compressedValue;
        if (log.isWarnEnabled()) {
            log.warn("close() using bzip2 and saving " + (l - bytes.length) + " bytes.");
        } // if
        l = bytes.length;
    } // if

    if (log.isInfoEnabled()) {
        if (marker == COMPRESSION_NONE) {
            if (log.isInfoEnabled()) {
                log.info("close() using no compression");
            } // if
        } // if
        if (marker == COMPRESSION_LZMA) {
            if (log.isInfoEnabled()) {
                log.info("close() using lzma");
            } // if
        } // if
    } // if

    ObjectOutputStream oos = new ObjectOutputStream(baseOutputStream);
    oos.writeByte(marker);
    oos.writeLong(originalBytes.length);
    oos.flush();
    OutputStream out = baseOutputStream;
    if (cipher != null) {
        out = new CipherOutputStream(out, cipher);
    } // if
    out.write(bytes);
    out.close();
    delegate = null;
    baseOutputStream = null;
}

From source file:idontwant2see.IDontWant2See.java

public void writeData(final ObjectOutputStream out) throws IOException {
    // sort the list so that often used entries are in the front (for faster lookup)
    Collections.sort(mSettings.getSearchList(), new Comparator<IDontWant2SeeListEntry>() {

        public int compare(IDontWant2SeeListEntry o1, IDontWant2SeeListEntry o2) {
            return o2.getLastMatchedDate().compareTo(o1.getLastMatchedDate());
        }/*from w ww .  jav  a  2s  .c o m*/
    });

    out.writeInt(7); //version
    out.writeInt(mSettings.getSearchList().size());

    for (IDontWant2SeeListEntry entry : mSettings.getSearchList()) {
        entry.writeData(out);
    }

    out.writeBoolean(mSettings.isSimpleMenu());
    out.writeBoolean(mSettings.isSwitchToMyFilter());

    out.writeUTF(mSettings.getLastEnteredExclusionString());

    mSettings.getLastUsedDate().writeData((DataOutput) out);

    out.writeByte(mSettings.getProgramImportance());
}

From source file:org.pentaho.reporting.engine.classic.core.Element.java

/**
 * A helper method that serializes the element object.
 *
 * @param stream/*from  w  ww  .j a v  a  2  s. c o m*/
 *          the stream to which the element should be serialized.
 * @throws IOException
 *           if an IO error occured or a property was not serializable.
 */
private void writeObject(final ObjectOutputStream stream) throws IOException {
    stream.defaultWriteObject();
    final ReportAttributeMap attributes = this.attributes;
    stream.writeLong(attributes.getChangeTracker());
    final String[] nameSpaces = attributes.getNameSpaces();
    stream.writeObject(nameSpaces);
    for (int i = 0; i < nameSpaces.length; i++) {
        final String nameSpace = nameSpaces[i];
        final String[] names = attributes.getNames(nameSpace);
        stream.writeObject(names);
        for (int j = 0; j < names.length; j++) {
            final String name = names[j];
            final Object attribute = attributes.getAttribute(nameSpace, name);

            final AttributeMetaData data = getMetaData().getAttributeDescription(nameSpace, name);
            if (data != null) {
                if (data.isTransient()) {
                    stream.writeByte(1);
                    continue;
                }

                if (attribute instanceof ResourceKey) {
                    final ResourceKey key = (ResourceKey) attribute;
                    final ResourceKey parent = key.getParent();
                    if (AttributeNames.Core.NAMESPACE.equals(nameSpace)
                            && (AttributeNames.Core.CONTENT_BASE.equals(name)
                                    || AttributeNames.Core.SOURCE.equals(name))) {
                        if (parent != null) {
                            // unwrap the content base attribute. After deserialization, the report assumes the bundle-location
                            // as content base, as the bundle will be gone.
                            if (isKeySerializable(parent)) {
                                stream.writeByte(0);
                                SerializerHelper.getInstance().writeObject(parent, stream);
                            } else {
                                stream.writeByte(1);
                            }
                        } else {
                            // great, the report was never part of a bundle. That makes life easier and the key should be
                            // safely serializable too.

                            if (isKeySerializable(key)) {
                                stream.writeByte(0);
                                SerializerHelper.getInstance().writeObject(key, stream);
                            } else {
                                stream.writeByte(1);
                            }
                        }
                    } else {
                        if ("Resource".equals(data.getValueRole()) || parent != null) {
                            stream.writeByte(0);
                            try {
                                final ResourceKey resourceKey = ResourceKeyUtils.embedResourceInKey(
                                        locateResourceManager(), key, key.getFactoryParameters());
                                SerializerHelper.getInstance().writeObject(resourceKey, stream);
                            } catch (ResourceException e) {
                                throw new IOException(
                                        "Failed to convert resource-key into byte-array key: " + e);
                            }
                        } else {
                            stream.writeByte(0);
                            SerializerHelper.getInstance().writeObject(attribute, stream);
                        }
                    }
                } else if (SerializerHelper.getInstance().isSerializable(attribute)) {
                    stream.writeByte(0);
                    SerializerHelper.getInstance().writeObject(attribute, stream);
                } else {
                    stream.writeByte(1);
                }
            } else if (attribute instanceof String) {
                stream.writeByte(0);
                SerializerHelper.getInstance().writeObject(attribute, stream);
            } else {
                stream.writeByte(1);
            }
        }
    }
}

From source file:org.pentaho.reporting.libraries.serializer.SerializerHelper.java

/**
 * Writes a serializable object description to the given object output stream. This method selects the best serialize
 * helper method for the given object.//from  w w w  .j ava 2s  .co m
 *
 * @param o   the to be serialized object.
 * @param out the outputstream that should receive the object.
 * @throws IOException if an I/O error occured.
 */
public synchronized void writeObject(final Object o, final ObjectOutputStream out) throws IOException {
    try {
        if (o == null) {
            out.writeByte(0);
            return;
        }
        if (o instanceof Serializable) {
            out.writeByte(1);
            out.writeObject(o);
            return;
        }

        final SerializeMethod m = getSerializer(o.getClass());
        if (m == null) {
            throw new NotSerializableException(o.getClass().getName());
        }
        out.writeByte(2);
        out.writeObject(m.getObjectClass());
        m.writeObject(o, out);
    } catch (NotSerializableException nse) {
        logger.warn("Unable to serialize object: " + o);
        throw nse;
    }
}