Example usage for java.io ObjectOutputStream flush

List of usage examples for java.io ObjectOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.threerings.media.tile.bundle.tools.TileSetBundler.java

/**
 * Create a tileset bundle jar file.//from  w  w  w  .  ja va  2 s.  c o m
 *
 * @param target the tileset bundle file that will be created.
 * @param bundle contains the tilesets we'd like to save out to the bundle.
 * @param improv the image provider.
 * @param imageBase the base directory for getting images for non-ObjectTileSet tilesets.
 * @param keepOriginalPngs bundle up the original PNGs as PNGs instead of converting to the
 * FastImageIO raw format
 */
public static boolean createBundleJar(File target, TileSetBundle bundle, ImageProvider improv, String imageBase,
        boolean keepOriginalPngs, boolean uncompressed) throws IOException {
    // now we have to create the actual bundle file
    FileOutputStream fout = new FileOutputStream(target);
    Manifest manifest = new Manifest();
    JarOutputStream jar = new JarOutputStream(fout, manifest);
    jar.setLevel(uncompressed ? Deflater.NO_COMPRESSION : Deflater.BEST_COMPRESSION);

    try {
        // write all of the image files to the bundle, converting the
        // tilesets to trimmed tilesets in the process
        Iterator<Integer> iditer = bundle.enumerateTileSetIds();

        // Store off the updated TileSets in a separate Map so we can wait to change the
        // bundle till we're done iterating.
        HashIntMap<TileSet> toUpdate = new HashIntMap<TileSet>();
        while (iditer.hasNext()) {
            int tileSetId = iditer.next().intValue();
            TileSet set = bundle.getTileSet(tileSetId);
            String imagePath = set.getImagePath();

            // sanity checks
            if (imagePath == null) {
                log.warning("Tileset contains no image path " + "[set=" + set + "]. It ain't gonna work.");
                continue;
            }

            // if this is an object tileset, trim it
            if (!keepOriginalPngs && (set instanceof ObjectTileSet)) {
                // set the tileset up with an image provider; we
                // need to do this so that we can trim it!
                set.setImageProvider(improv);

                // we're going to trim it, so adjust the path
                imagePath = adjustImagePath(imagePath);
                jar.putNextEntry(new JarEntry(imagePath));

                try {
                    // create a trimmed object tileset, which will
                    // write the trimmed tileset image to the jar
                    // output stream
                    TrimmedObjectTileSet tset = TrimmedObjectTileSet.trimObjectTileSet((ObjectTileSet) set,
                            jar);
                    tset.setImagePath(imagePath);
                    // replace the original set with the trimmed
                    // tileset in the tileset bundle
                    toUpdate.put(tileSetId, tset);

                } catch (Exception e) {
                    e.printStackTrace(System.err);

                    String msg = "Error adding tileset to bundle " + imagePath + ", " + set.getName() + ": "
                            + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }

            } else {
                // read the image file and convert it to our custom
                // format in the bundle
                File ifile = new File(imageBase, imagePath);
                try {
                    BufferedImage image = ImageIO.read(ifile);
                    if (!keepOriginalPngs && FastImageIO.canWrite(image)) {
                        imagePath = adjustImagePath(imagePath);
                        jar.putNextEntry(new JarEntry(imagePath));
                        set.setImagePath(imagePath);
                        FastImageIO.write(image, jar);
                    } else {
                        jar.putNextEntry(new JarEntry(imagePath));
                        FileInputStream imgin = new FileInputStream(ifile);
                        StreamUtil.copy(imgin, jar);
                    }
                } catch (Exception e) {
                    String msg = "Failure bundling image " + ifile + ": " + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }
            }
        }
        bundle.putAll(toUpdate);

        // now write a serialized representation of the tileset bundle
        // object to the bundle jar file
        JarEntry entry = new JarEntry(BundleUtil.METADATA_PATH);
        jar.putNextEntry(entry);
        ObjectOutputStream oout = new ObjectOutputStream(jar);
        oout.writeObject(bundle);
        oout.flush();

        // finally close up the jar file and call ourself done
        jar.close();

        return true;

    } catch (Exception e) {
        // remove the incomplete jar file and rethrow the exception
        jar.close();
        if (!target.delete()) {
            log.warning("Failed to close botched bundle '" + target + "'.");
        }
        String errmsg = "Failed to create bundle " + target + ": " + e;
        throw (IOException) new IOException(errmsg).initCause(e);
    }
}

From source file:com.dev.pygmy.util.Utils.java

/**
 * Saves the current game by serializing it and storing in locally
 * on the device//from  w  w  w.  j ava2 s.  c o m
 */
public static void saveGame(PygmyGame game, String path) {
    ObjectOutputStream oos = null;
    try {
        File history = new File(path);
        history.getParentFile().createNewFile();
        FileOutputStream fout = new FileOutputStream(history);
        oos = new ObjectOutputStream(fout);
        oos.writeObject(game);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (oos != null) {
                oos.flush();
                oos.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.apache.ignite.GridTestIoUtils.java

/**
 * Serializes a given object into byte array.
 *
 * @param obj Object to serialize./*w  ww . ja  va2  s.com*/
 * @return Byte array containing serialized object.
 * @throws IOException If serialization failed.
 */
public static byte[] serializeJdk(Object obj) throws IOException {
    ByteArrayOutputStream byteOut = null;

    ObjectOutputStream objOut = null;

    try {
        // Allocate half of kilobyte to avoid very small resizings.
        byteOut = new ByteArrayOutputStream(512);

        objOut = new ObjectOutputStream(byteOut);

        // Make sure that we serialize only task, without
        // class loader.
        objOut.writeObject(obj);

        objOut.flush();

        return byteOut.toByteArray();
    } finally {
        close(objOut);
        close(byteOut);
    }
}

From source file:com.beetle.framework.util.ObjectUtil.java

/**
 * ??/*from ww w .j av a2s .  c o  m*/
 * 
 * @param obj
 * @return
 */
public final static byte[] objToBytes(Object obj) {
    ByteArrayOutputStream bao = null;
    ObjectOutputStream oos;
    try {
        bao = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bao);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        return bao.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (bao != null) {
                bao.close();
                bao = null;
            }
        } catch (IOException e) {
        }
    }
}

From source file:com.beetle.framework.util.ObjectUtil.java

/**
 * ???/*from   w w  w  .ja  v a2s . co m*/
 * 
 * @param obj
 * @return
 */
public final static int sizeOf(Object obj) {
    ByteArrayOutputStream bao = null;
    ObjectOutputStream oos;
    try {
        bao = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bao);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
        return bao.size();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    } finally {
        try {
            if (bao != null) {
                bao.close();
                bao = null;
            }
        } catch (IOException e) {
        }
    }
}

From source file:org.underworldlabs.util.FileUtils.java

public static void writeObject(Object object, String path) throws IOException {

    FileOutputStream fileOut = null;
    BufferedOutputStream bufferedOut = null;
    ObjectOutputStream objectOut = null;

    try {//  w  w  w .  j a va 2s. c  o  m

        fileOut = new FileOutputStream(path);
        bufferedOut = new BufferedOutputStream(fileOut);
        objectOut = new ObjectOutputStream(bufferedOut);
        objectOut.writeObject(object);
        objectOut.flush();

    } finally {

        try {
            if (objectOut != null) {
                objectOut.close();
            }
            if (bufferedOut != null) {
                bufferedOut.close();
            }
            if (fileOut != null) {
                fileOut.close();
            }
        } catch (IOException e) {
        }

    }

}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.TaskUtils.java

/**
 * Saves a serializable object of type <T> to disk. Output file may be uncompressed, gzipped or
 * bz2-compressed. Compressed files must have a .gz or .bz2 suffix.
 *
 * @param serializedFile/*from   w  ww .  ja  v a2  s.  com*/
 *            model output file
 * @param serializableObject
 *            the object to serialize
 * @throws IOException
 */
public static void serialize(File serializedFile, Object serializableObject) throws IOException {

    FileOutputStream fos = new FileOutputStream(serializedFile);
    BufferedOutputStream bufStr = new BufferedOutputStream(fos);

    OutputStream underlyingStream = null;
    if (serializedFile.getName().endsWith(".gz")) {
        underlyingStream = new GZIPOutputStream(bufStr);
    } else if (serializedFile.getName().endsWith(".bz2")) {
        underlyingStream = new CBZip2OutputStream(bufStr);
        // manually add bz2 prefix to make it compatible to normal bz2 tools
        // prefix has to be skipped when reading the stream with CBZip2
        fos.write("BZ".getBytes("UTF-8"));
    } else {
        underlyingStream = bufStr;
    }
    ObjectOutputStream serializer = new ObjectOutputStream(underlyingStream);
    try {
        serializer.writeObject(serializableObject);

    } finally {
        serializer.flush();
        serializer.close();
    }
}

From source file:com.gamesalutes.utils.ByteUtils.java

/**
 * Returns a <code>ByteBuffer</code> containing the byte representation
 * of the serializable object <code>obj</code>.
 * //from ww w .j  a  va2s  . c om
 * @param obj the <code>Object</code> to convert to its byte representation
 * @param buf an existing buffer to use for storage or <code>null</code> to create new buffer.
 *        If <code>buf</code> is not large enough it will be expanded using {@link #growBuffer(ByteBuffer, int)}
 * @return <code>ByteBuffer</code> containing the byte representation
 * of <code>obj</code>.
 * 
 * @throws IOException if <code>obj</code> is not serializable or error occurs while writing the bytes
 */
public static ByteBuffer getObjectBytes(Object obj, ByteBuffer buf) throws IOException {
    if (buf == null)
        buf = ByteBuffer.allocate(READ_BUFFER_SIZE);

    // note the input position
    int startPos = buf.position();
    ByteBufferChannel channel = new ByteBufferChannel(buf);
    ObjectOutputStream out = null;
    try {
        out = new ObjectOutputStream(Channels.newOutputStream(channel));
        out.writeObject(obj);
        out.flush();
    } finally {
        MiscUtils.closeStream(out);
    }

    ByteBuffer returnBuf = channel.getByteBuffer();
    returnBuf.flip();
    // reset starting position to be that of input buffer
    returnBuf.position(startPos);
    return returnBuf;
}

From source file:org.pgptool.gui.config.impl.ConfigRepositoryImpl.java

public static void writeObject(Object o, String destinationFile) {
    ObjectOutputStream oos = null;
    try {/*from  w  w  w .  j  a  v  a2s . co  m*/
        log.trace(String.format("Persisting %s to %s", o, destinationFile));

        File file = new File(destinationFile);
        if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
            throw new RuntimeException("Failed to create all parent directories");
        }

        FileOutputStream fout = new FileOutputStream(file);
        oos = new ObjectOutputStream(fout);
        oos.writeObject(o);
        oos.flush();
        oos.close();
        fout.close();
    } catch (Throwable t) {
        throw new RuntimeException("Failed to write config: " + destinationFile, t);
    } finally {
        safeClose(oos);
    }
}

From source file:com.sec.ose.osi.sdk.protexsdk.component.ComponentAPIWrapper.java

public static void save() {
    ObjectOutputStream oos;
    try {/*from  w w w  .j av a  2 s  .c o  m*/
        oos = new ObjectOutputStream(new FileOutputStream(new File(COMPONENT_FILE_PATH)));
        for (ComponentInfo tmp : globalComponentManager.getComponentList()) {
            oos.writeObject(tmp);
        }
        oos.flush();
        oos.close();
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}