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:org.lmn.fc.common.datatranslators.DataExporter.java

/***********************************************************************************************
 * exportStringBuffer()./*from w w w . j  a  v a 2s. c om*/
 * Saves the StringBuffer at the specified location.
 *
 * @param filename
 * @param timestamp
 * @param format
 * @param buffer
 * @param log
 * @param clock
 *
 * @return boolean
 */

public static boolean exportStringBuffer(final String filename, final boolean timestamp,
        final DataFormat format, final StringBuffer buffer, final Vector<Vector> log,
        final ObservatoryClockInterface clock) {
    final String SOURCE = "DataExporter.exportStringBuffer()";
    boolean boolSuccess;

    boolSuccess = false;

    if ((filename != null) && (!EMPTY_STRING.equals(filename)) && (format != null) && (buffer != null)
            && (buffer.length() > 0) && (log != null) && (clock != null)) {
        try {
            final File file;
            final OutputStream outputStream;

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

            outputStream.write(buffer.toString().getBytes());

            boolSuccess = true;

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

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

        catch (SecurityException exception) {
            SimpleEventLogUIComponent.logEvent(log, EventStatus.FATAL,
                    METADATA_TARGET + format.getFileExtension() + TERMINATOR + 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 + format.getFileExtension() + TERMINATOR + 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 + format.getFileExtension() + TERMINATOR + 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 + format.getFileExtension() + TERMINATOR
                                + METADATA_ACTION_EXPORT + METADATA_RESULT + ERROR_XML + TERMINATOR,
                        SOURCE, clock);
    }

    return (boolSuccess);
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Copy the contents of the given InputStream to the given OutputStream.
 * Closes both streams when done./*from  w  w  w  .  j a  v  a 2 s  .  co m*/
 *
 * @param in  the stream to copy from
 * @param out the stream to copy to
 * @return the number of bytes copied
 * @throws java.io.IOException in case of I/O errors
 */
public static long copy(InputStream in, OutputStream out) throws IOException {
    try {
        int byteCount = 0;
        byte[] buffer = new byte[FOUR_KB];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        return byteCount;
    } finally {
        close(in);
        close(out);
    }
}

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

/**
 * Transfers all data from <code>is</code> to </code>os</code>.
 * <code>is</code> is closed as a result of invoking this operation.
 *
 * @param is the <code>InputStream</code>
 * @param os the <code>OutputStream</code>
 * @param maxBytes approximate maximum number of bytes to transfer or <code>-1</code> to not set a limit
 *
 *///  www. j a va 2 s. c om
public static void transferData(InputStream is, OutputStream os, long maxBytes) throws IOException {
    byte[] buf = new byte[NETWORK_BYTE_SIZE];

    int read;
    long totalRead = 0;

    try {
        while ((read = is.read(buf)) > 0) {
            os.write(buf, 0, read);
            totalRead += read;
            if (maxBytes > 0 && totalRead > maxBytes) {
                throw new IOException("maxBytes=" + maxBytes + " exceeded");
            }
        }
        os.flush();
    } finally {
        MiscUtils.closeStream(is);
    }
}

From source file:delphsim.model.Resultado.java

/**
 * Mtodo esttico que exporta una grfica <CODE>JFreeChart</CODE> al
 * formato de imagen vectorial SVG./*  w  w  w  . ja v  a 2  s. c  om*/
 * @param destino El fichero de destino.
 * @param chart La grfica a exportar.
 * @param anchura Anchura de la imagen final.
 * @param altura Altura de la imagen final.
 * @throws java.io.IOException Si hubiera algn problema al crear el archivo en disco.
 */
public static void exportarComoSVG(File destino, JFreeChart chart, int anchura, int altura) throws IOException {
    // Para SVG utilizamos la librera Batik
    // Obtener un DOMImplementation
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    // Crear una instancia de org.w3c.dom.Document
    String svgNS = "http://www.w3.org/2000/svg";
    Document document = domImpl.createDocument(svgNS, "svg", null);
    // Crear una instancia del Generador de SVGs
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
    // Dibujar la grfica en el Generador de SVGs
    chart.draw(svgGenerator, new Rectangle(anchura, altura));
    // Escribir el archivo SVG
    OutputStream outputStream = new FileOutputStream(destino);
    Writer out = new OutputStreamWriter(outputStream, "UTF-8");
    svgGenerator.stream(out, true /* utilizar CSS */);
    outputStream.flush();
    outputStream.close();
}

From source file:de.unirostock.sems.cbarchive.web.Tools.java

/**
 * Copies an InputStream into an OutputStream and closes all streams afterwards.
 * Stops at max length./*  w ww  .  j  a  v  a  2 s .  c o  m*/
 *
 * @param input the input
 * @param output the output
 * @param maxLength the max length
 * @return the size of the stream copied
 * @throws IOException the IO exception
 */
public static long copyStream(InputStream input, OutputStream output, long maxLength) throws IOException {

    byte[] buffer = new byte[Fields.DEFAULT_BUFFER_SIZE];
    long copied = 0;
    int red = 0;
    while ((red = input.read(buffer)) != -1) {
        output.write(buffer, 0, red);

        copied = copied + red;
        // abort, if maxLength is reached
        if (maxLength > 0 && copied > maxLength)
            break;
    }

    input.close();
    output.flush();
    output.close();

    return copied;
}

From source file:biz.bokhorst.xprivacy.Util.java

public static String importProLicense(File licenseFile) {
    // Get imported license file name
    String importedLicense = getUserDataDirectory(Process.myUid()) + File.separator + LICENSE_FILE_NAME;
    File out = new File(importedLicense);

    // Check if license file exists
    if (licenseFile.exists() && licenseFile.canRead()) {
        try {/*from w w  w .j a  v  a 2s  . c  om*/
            // Import license file
            Util.log(null, Log.WARN, "Licensing: importing " + out.getAbsolutePath());
            InputStream is = null;
            is = new FileInputStream(licenseFile.getAbsolutePath());
            try {
                OutputStream os = null;
                try {
                    os = new FileOutputStream(out.getAbsolutePath());
                    byte[] buffer = new byte[1024];
                    int read;
                    while ((read = is.read(buffer)) != -1)
                        os.write(buffer, 0, read);
                    os.flush();
                } finally {
                    if (os != null)
                        os.close();
                }
            } finally {
                if (is != null)
                    is.close();
            }

            // Protect imported license file
            setPermissions(out.getAbsolutePath(), 0700, Process.myUid(), Process.myUid());

            // Remove original license file
            licenseFile.delete();
        } catch (FileNotFoundException ignored) {
        } catch (Throwable ex) {
            Util.bug(null, ex);
        }
    }

    return (out.exists() && out.canRead() ? importedLicense : null);
}

From source file:org.bibalex.gallery.storage.BAGStorage.java

public static void readRemoteFile(String fileUrlStr, OutputStream localOut) throws BAGException {
    try {//from   w  ww  .java2 s. c  om
        try {
            FileObject imageFO;

            imageFO = VFS.getManager().resolveFile(fileUrlStr);

            InputStream imageIS = imageFO.getContent().getInputStream();

            byte buffer[] = new byte[10240];
            int bytesRead = 0;
            do {
                bytesRead = imageIS.read(buffer);

                if (bytesRead > 0) {
                    localOut.write(buffer, 0, bytesRead);
                } else {
                    break;
                }
            } while (true);

        } finally {
            localOut.flush();
        }

    } catch (FileSystemException e) {
        throw new BAGException(e);
    } catch (IOException e) {
        throw new BAGException(e);

    }
}

From source file:ZipSocket.java

public synchronized void close() throws IOException {
    OutputStream o = getOutputStream();
    o.flush();
    super.close();
}

From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.java

/**
 * <pre>/*from w  w w.j  ava2 s  .c om*/
 * Add a multipart and write it to output of a connection.
 *
 * NOTE : It only supports chunked transfer encoding mode,
 *        the server should supports it.
 * </pre>
 */
private static void addMultipartIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    OutputStream os = null;
    try {
        if (!(request instanceof MultipartContainer)) {
            return;
        }

        MultipartContainer container = (MultipartContainer) request;
        if (!container.hasMultipart()) {
            return;
        }

        Multipart multipart = container.getMultipart();
        if (multipart == null) {
            return;
        }

        connection.setDoOutput(true);
        connection.addRequestProperty("Content-Type", multipart.getContentType());
        // Set chunked encoding mode.
        connection.setChunkedStreamingMode(DEFAULT_CHUNK_LENGTH);
        os = connection.getOutputStream();
        multipart.write(os);
        os.flush();
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

From source file:de.uka.ilkd.key.dl.gui.initialdialog.gui.ToolInstaller.java

/**
 * @param tmp/* ww w .jav a2s . c o m*/
 * @param dir
 * @throws IOException
 * @throws ArchiveException
 */
private static void untar(File file, File dir, FileType ft, PropertySetter ps, JProgressBar bar)
        throws IOException, ArchiveException {
    FileInputStream fis = new FileInputStream(file);
    InputStream is;
    switch (ft) {
    case TARGZ:
        is = new GZIPInputStream(fis);
        break;
    case TARBZ2:
        is = new BZip2CompressorInputStream(fis);
        break;
    default:
        throw new IllegalArgumentException("Don't know how to handle filetype: " + ft);
    }

    final TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream("tar", is);
    TarArchiveEntry entry = null;
    int value = 0;
    while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
        bar.setValue(value++);
        final File outputFile = new File(dir, entry.getName());
        if (entry.isDirectory()) {
            if (!outputFile.exists()) {
                if (!outputFile.mkdirs()) {
                    throw new IllegalStateException(
                            String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                }
            }
        } else {
            final OutputStream outputFileStream = new FileOutputStream(outputFile);
            IOUtils.copy(debInputStream, outputFileStream);
            if (OSInfosDefault.INSTANCE.getOs() == OperatingSystem.OSX) {
                // FIXME: we need to make everything executable as somehow
                // the executable bit is not preserved in
                // OSX
                outputFile.setExecutable(true);
            }
            if (ps.filterFilename(outputFile)) {
                ps.setProperty(outputFile.getAbsolutePath());
            }
            outputFileStream.flush();
            outputFileStream.close();
        }
    }
    debInputStream.close();
    is.close();
    file.delete();
}