Example usage for java.io OutputStream flush

List of usage examples for java.io OutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.heliosapm.tsdblite.json.JSON.java

/**
 * Serializes the passed object as JSON into the passed buffer
 * @param obj The object to serialize/*w w w .  j a v  a  2 s. c  o m*/
 * @param buf The buffer to serialize into. If null, a new buffer is created
 * @return The buffer the object was written to
 */
public static ByteBuf serializeToBuf(final Object obj, final ByteBuf buf) {
    if (obj == null)
        throw new IllegalArgumentException("The passed object was null");
    final ByteBuf b = buf == null ? Unpooled.directBuffer(2048) : buf;
    OutputStream os = null;
    try {
        os = new ByteBufOutputStream(b);
        serialize(obj, os);
        os.flush();
        return b;
    } catch (Exception ex) {
        throw new RuntimeException("Failed to bufferize serialized object", ex);
    } finally {
        if (os != null)
            try {
                os.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:crow.util.Util.java

public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException {
    int responseCode = -1;
    OutputStream osw = null;
    try {/*from   ww w.jav  a  2 s . c  o  m*/
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(12000);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        byte[] bytes = encodePostParam.getBytes("UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        osw = conn.getOutputStream();
        osw.write(bytes);
        osw.flush();
        responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("");
        } else {
            String s = inputStreamToString(conn.getInputStream());
            return s;
        }
    } finally {
        try {
            if (osw != null)
                osw.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:Main.java

private static void loadICUData(Context context, File destDir) throws IOException {
    OutputStream out = null;
    ZipInputStream in = null;/*from w ww . j  a va 2  s  .co m*/
    File icuDir = new File(destDir, "icu");
    File icuDataFile = new File(icuDir, "icudt53l.dat");
    try {
        if (!icuDir.exists())
            icuDir.mkdirs();
        if (!icuDataFile.exists()) {
            in = new ZipInputStream(context.getAssets().open("icudt53l.zip"));
            in.getNextEntry();
            out = new FileOutputStream(icuDataFile);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
    } catch (IOException e) {
        if (icuDataFile.exists())
            icuDataFile.delete();
        throw e;
    } finally {
        if (in != null)
            in.close();
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:com.xiaomi.account.utils.SysHelper.java

public static File saveAsFile(Context context, InputStream imgStream, String filename) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(imgStream);
    OutputStream os = new BufferedOutputStream(context.openFileOutput(filename, 0));
    byte[] buffer = new byte[1024];
    while (true) {
        try {//w w w . j  a  va 2s  .c om
            int count = bis.read(buffer);
            if (count == -1) {
                break;
            }
            os.write(buffer, 0, count);
        } finally {
            try {
                os.flush();
            } catch (IOException e) {
            }
            try {
                os.close();
            } catch (IOException e2) {
            }
        }
    }
    try {
        os.close();
    } catch (IOException e3) {
    }
    return context.getFileStreamPath(filename);
}

From source file:FileUtils.java

/**
 * Copy any input stream to output stream. Once the data will be copied
 * both streams will be closed.//from   w  w  w  . j  av  a2s  .  c  om
 * 
 * @param input  - InputStream to copy from
 * @param output - OutputStream to copy to
 * @throws IOException - io error in function
 * @throws OSSMultiException - double error in function
 */
public static void copyStreamToStream(InputStream input, OutputStream output) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    int ch;

    try {
        if (input instanceof BufferedInputStream) {
            is = input;
        } else {
            is = new BufferedInputStream(input);
        }
        if (output instanceof BufferedOutputStream) {
            os = output;
        } else {
            os = new BufferedOutputStream(output);
        }

        while ((ch = is.read()) != -1) {
            os.write(ch);
        }
        os.flush();
    } finally {
        IOException exec1 = null;
        IOException exec2 = null;
        try {
            // because this close can throw exception we do next close in 
            // finally statement
            if (os != null) {
                try {
                    os.close();
                } catch (IOException exec) {
                    exec1 = exec;
                }
            }
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException exec) {
                    exec2 = exec;
                }
            }
        }
        if ((exec1 != null) && (exec2 != null)) {
            throw exec1;
        } else if (exec1 != null) {
            throw exec1;
        } else if (exec2 != null) {
            throw exec2;
        }
    }
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

/**
 * Copy an input stream to an output stream
 *
 * @param copyFrom// w  w  w .j a  v  a2s .  c  o  m
 * @param copyTo
 * @throws IOException
 */
public static void copyStream(InputStream copyFrom, OutputStream copyTo) throws IOException {

    byte[] buffer = new byte[1024];
    int length;
    while ((length = copyFrom.read(buffer)) > 0) {
        copyTo.write(buffer, 0, length);
    }

    copyTo.flush();
    copyTo.close();
    copyFrom.close();
}

From source file:de.matzefratze123.staffinformer.util.I18N.java

private static void copyLanguageXml(File destFile) {
    InputStream inStream = null;/*from  w w w.ja v  a2  s  .c  o m*/
    OutputStream outStream = null;

    try {
        destFile.createNewFile();

        inStream = I18N.class.getResourceAsStream('/' + MESSAGES_FILE);
        outStream = new FileOutputStream(destFile);

        final byte[] BUFFER = new byte[1024];
        int read;

        while ((read = inStream.read(BUFFER)) > 0) {
            outStream.write(BUFFER, 0, read);
        }
    } catch (IOException e) {
        Logger.severe("Failed to copy messages file! Using default messages...");
        e.printStackTrace();
    } finally {
        try {
            if (inStream != null) {
                inStream.close();
            }

            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:de.matzefratze123.heavyspleef.util.I18NNew.java

private static void copyLanguageXml(File destFile) {
    InputStream inStream = null;/*from   w  w  w.  j  av a2s . com*/
    OutputStream outStream = null;

    try {
        destFile.createNewFile();

        inStream = I18NNew.class.getResourceAsStream('/' + MESSAGES_FILE);
        outStream = new FileOutputStream(destFile);

        final byte[] BUFFER = new byte[1024];
        int read;

        while ((read = inStream.read(BUFFER)) > 0) {
            outStream.write(BUFFER, 0, read);
        }
    } catch (IOException e) {
        Logger.severe("Failed to copy messages file! Using default messages...");
        e.printStackTrace();
    } finally {
        try {
            if (inStream != null) {
                inStream.close();
            }

            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:org.lmn.fc.common.datatranslators.DataExporter.java

/***********************************************************************************************
 * exportInstrumentXML()./*w w  w.j  a va 2 s  .  c o  m*/
 * Saves the current Instrument XML at the specified location.
 *
 * @param filename
 * @param timestamp
 * @param instrument
 * @param log
 * @param clock
 *
 * @return boolean
 */

public static boolean exportInstrumentXML(final String filename, final boolean timestamp,
        final Instrument instrument, final Vector<Vector> log, final ObservatoryClockInterface clock) {
    final String SOURCE = "DataExporter.exportInstrumentXML()";
    boolean boolSuccess;

    boolSuccess = false;

    if ((filename != null) && (!EMPTY_STRING.equals(filename)) && (instrument != null) && (log != null)
            && (clock != null)) {
        try {
            final File file;
            final OutputStream outputStream;

            file = new File(FileUtilities.buildFullFilename(filename, timestamp, DataFormat.XML));
            FileUtilities.overwriteFile(file);
            outputStream = new FileOutputStream(file);

            instrument.save(outputStream, getXmlOptions());

            boolSuccess = true;

            // Tidy up
            outputStream.flush();
            outputStream.close();

            SimpleEventLogUIComponent.logEvent(log, EventStatus.INFO, METADATA_TARGET_XML
                    + METADATA_ACTION_EXPORT + METADATA_FILENAME + file.getAbsolutePath() + TERMINATOR, SOURCE,
                    clock);
        }

        catch (SecurityException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_XML + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_ACCESS_DENIED
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (FileNotFoundException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_XML + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_NOT_FOUND
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }

        catch (IOException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET_XML + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_FILE_SAVE
                            + TERMINATOR + SPACE + METADATA_EXCEPTION + exception.getMessage() + TERMINATOR,
                    SOURCE, clock);
        }
    } else {
        SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                METADATA_TARGET_XML + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_XML + TERMINATOR, SOURCE,
                clock);
    }

    return (boolSuccess);
}

From source file:net.openchrom.xxd.processor.supplier.rscripting.ui.code.RServe.java

/**
 * Evaluates and prints an expression to the Plugin console executed in a job.
 * //  w  ww . j av a  2  s  .  c o m
 * @param expression
 *            a R expression as a string.
 */
public static void printJob(String expression) {// helper class to print

    if (RState.isBusy() == false) {
        RState.setBusy(true);
        REvaluateJob job = new REvaluateJob(expression);
        job.addJobChangeListener(new JobChangeAdapter() {

            public void done(IJobChangeEvent event) {

                if (event.getResult().isOK()) {
                    int countDev = getDisplayNumber();
                    RState.setBusy(false);
                    if (countDev > 0) {
                        RServe.closeAndDisplay();
                    }
                    System.out.flush();
                } else {
                    RState.setBusy(false);
                    System.out.flush();
                }
            }
        });
        // job.setSystem(true);
        job.schedule();
    } else {
        Process p;
        IPreferenceStore store = Activator.getDefault().getPreferenceStore();
        if (store.getBoolean("RSERVE_NATIVE_START")) {
            ConsolePageParticipant consol = ConsolePageParticipant.getConsolePageParticipantInstance();
            p = consol.getRProcess();
        } else {
            p = RConnectionJob.getProc();
        }
        // Write to the output!
        if (p != null) {
            final OutputStream os = p.getOutputStream();
            final OutputStreamWriter osw = new OutputStreamWriter(os);
            final BufferedWriter bw = new BufferedWriter(osw, 100);
            try {
                bw.write(expression);
                bw.newLine();
                os.flush();
                bw.flush();
                // bw.close();
                System.out.flush();
            } catch (IOException e) {
                System.err.println("");
            }
        }
        MsgDialog.message("Rserve is busy!");
    }
}