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:net.orpiske.ssps.common.archive.TarArchiveUtils.java

/**
 * Lower level pack operation/*w  w  w.  j  a  va2s.  com*/
 * 
 * @param source
 *            source file
 * @param destination
 *            destination file
 * @return the number of bytes processed
 * @throws ArchiveException
 * @throws IOException
 */
public static long pack(String source, File destination) throws ArchiveException, IOException {

    ArchiveStreamFactory factory = new ArchiveStreamFactory();

    OutputStream outStream = new FileOutputStream(destination);

    ArchiveOutputStream outputStream;
    try {
        outputStream = factory.createArchiveOutputStream(ArchiveStreamFactory.TAR, outStream);
    } catch (ArchiveException e) {
        IOUtils.closeQuietly(outStream);

        throw e;
    }

    File startDirectory = new File(source);

    RecursiveArchiver archiver = new RecursiveArchiver(outputStream);

    try {
        archiver.archive(startDirectory);
        outputStream.flush();
        outputStream.close();

        outStream.flush();
        outStream.close();

    } catch (IOException e) {
        IOUtils.closeQuietly(outStream);
        IOUtils.closeQuietly(outputStream);

        throw e;
    }

    long ret = outputStream.getBytesWritten();

    if (logger.isDebugEnabled()) {
        logger.debug("Packed " + ret + " bytes");
    }

    return ret;
}

From source file:it.geosolutions.tools.io.file.IOUtils.java

/**
 * Copy {@link InputStream} to {@link OutputStream}.
 * //  ww  w .j  a  va 2s  .  c o  m
 * @param sourceStream
 *            {@link InputStream} to copy from.
 * @param destinationStream
 *            {@link OutputStream} to copy to.
 * @param size
 *            size of the buffer to use internally.
 * @param closeInput
 *            quietly close {@link InputStream}.
 * @param closeOutput
 *            quietly close {@link OutputStream}
 * @throws IOException
 *             in case something bad happens.
 */
public static void copyStream(InputStream sourceStream, OutputStream destinationStream, int size,
        boolean closeInput, boolean closeOutput) throws IOException {

    Objects.notNull(sourceStream, destinationStream);
    byte[] buf = new byte[size];
    int n = -1;
    try {
        while (-1 != (n = sourceStream.read(buf))) {
            destinationStream.write(buf, 0, n);
            destinationStream.flush();
        }
    } finally {
        // closing streams and connections
        try {
            destinationStream.flush();
        } finally {
            try {
                if (closeOutput)
                    destinationStream.close();
            } finally {
                try {
                    if (closeInput)
                        sourceStream.close();
                } finally {

                }
            }
        }
    }
}

From source file:com.netsteadfast.greenstep.util.JReportUtils.java

public static void deployReport(TbSysJreport report) throws Exception {
    String reportDeployDirName = Constants.getDeployJasperReportDir() + "/";
    File reportDeployDir = new File(reportDeployDirName);
    try {/*from ww  w .j a va2 s . c  o  m*/
        if (!reportDeployDir.exists()) {
            logger.warn("no exists dir, force mkdir " + reportDeployDirName);
            FileUtils.forceMkdir(reportDeployDir);
        }
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage().toString());
    }
    logger.info("REPORT-ID : " + report.getReportId());
    File reportFile = null;
    File reportZipFile = null;
    OutputStream os = null;
    try {
        String reportFileFullPath = reportDeployDirName + report.getReportId() + "/" + report.getFile();
        String reportZipFileFullPath = reportDeployDirName + report.getReportId() + ".zip";
        reportZipFile = new File(reportZipFileFullPath);
        if (reportZipFile.exists()) {
            logger.warn("delete " + reportZipFileFullPath);
            FileUtils.forceDelete(reportZipFile);
        }
        os = new FileOutputStream(reportZipFile);
        IOUtils.write(report.getContent(), os);
        os.flush();
        ZipFile zipFile = new ZipFile(reportZipFileFullPath);
        zipFile.extractAll(reportDeployDirName);
        reportFile = new File(reportFileFullPath);
        if (!reportFile.exists()) {
            logger.warn("report file is missing : " + reportFileFullPath);
            return;
        }
        if (YesNo.YES.equals(report.getIsCompile()) && report.getFile().endsWith("jrxml")) {
            logger.info("compile report...");
            String outJasper = compileReportToJasperFile(new String[] { reportFileFullPath },
                    reportDeployDirName + report.getReportId() + "/");
            logger.info("out : " + outJasper);
        }
    } catch (JRException re) {
        re.printStackTrace();
        logger.error(re.getMessage().toString());
    } catch (IOException e) {
        e.printStackTrace();
        logger.error(e.getMessage().toString());
    } finally {
        if (os != null) {
            os.close();
        }
        os = null;
        reportFile = null;
        reportZipFile = null;
    }
    reportDeployDir = null;
}

From source file:com.viettel.dms.download.DownloadFile.java

public static void copyStream(InputStream is, OutputStream os, byte[] buffer, int bufferSize)
        throws IOException {
    try {//from w w w. jav  a 2  s.c o m
        for (;;) {
            int count = is.read(buffer, 0, bufferSize);
            if (count == -1) {
                break;
            }
            os.write(buffer, 0, count);
        }
        os.flush();
    } catch (IOException e) {
        throw e;
    }
}

From source file:org.frameworkset.spi.remote.http.Client.java

public static String getFileContent(InputStream reader, String charSet) throws IOException {
    ByteArrayOutputStream swriter = null;
    OutputStream temp = null;

    try {/*from ww w  .j  a  v a  2  s  .c o  m*/
        //           reader = new FileInputStream(file);
        swriter = new ByteArrayOutputStream();
        temp = new BufferedOutputStream(swriter);

        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = reader.read(buffer)) > 0) {
            temp.write(buffer, 0, len);
        }
        temp.flush();
        if (charSet != null && !charSet.equals(""))
            return swriter.toString(charSet);
        else
            return swriter.toString();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return "";
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (reader != null)
            try {
                reader.close();
            } catch (IOException e) {
            }
        if (swriter != null)
            try {
                swriter.close();
            } catch (IOException e) {
            }
        if (temp != null)
            try {
                temp.close();
            } catch (IOException e) {
            }
    }
}

From source file:jeeves.utils.BinaryFile.java

private static void copy(InputStream inScp, OutputStream outScp, OutputStream output) throws IOException {
    byte[] buf = new byte[1024];

    // send '\0' to scp
    buf[0] = 0;//  www .  ja va  2  s  .c  o  m
    outScp.write(buf, 0, 1);
    outScp.flush();
    while (true) {
        int c = checkAck(inScp);
        if (c != 'C')
            break;
        // read '0644 ' from scp
        if (inScp.read(buf, 0, 5) == -1) {
            throw new IllegalStateException("Expected 0664 but got nothing");
        }

        // establish file size from scp
        long filesize = 0L;
        while (true) {
            if (inScp.read(buf, 0, 1) < 0) {
                // error from scp
                break;
            }
            if (buf[0] == ' ')
                break;
            filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        // now get file name from scp
        String file = null;
        for (int i = 0;; i++) {
            if (inScp.read(buf, i, 1) == -1) {
                throw new IllegalStateException("Unable to read file name");
            }
            if (buf[i] == (byte) 0x0a) {
                file = new String(buf, 0, i, Charset.forName("UTF-8"));
                break;
            }
        }

        // now get file name from scp 
        if (Log.isDebugEnabled(Log.RESOURCES))
            Log.debug(Log.RESOURCES, "scp: file returned has filesize=" + filesize + ", file=" + file);

        // send '\0'
        buf[0] = 0;
        outScp.write(buf, 0, 1);
        outScp.flush();

        // read contents from scp
        int foo;
        while (true) {
            if (buf.length < filesize)
                foo = buf.length;
            else
                foo = (int) filesize;
            foo = inScp.read(buf, 0, foo);
            if (foo < 0) {
                // error
                break;
            }
            output.write(buf, 0, foo);
            filesize -= foo;
            if (filesize == 0L)
                break;
        }
        if (checkAck(inScp) == 0) {
            // send '\0'
            buf[0] = 0;
            outScp.write(buf, 0, 1);
            outScp.flush();
        }
    }
}

From source file:au.gov.ansto.bragg.nbi.restlet.fileupload.util.Streams.java

/**
 * Copies the contents of the given {@link InputStream}
 * to the given {@link OutputStream}./*from w  w w  .  j a va  2s.  c o m*/
 *
 * @param inputStream The input stream, which is being read.
 *   It is guaranteed, that {@link InputStream#close()} is called
 *   on the stream.
 * @param outputStream The output stream, to which data should
 *   be written. May be null, in which case the input streams
 *   contents are simply discarded.
 * @param closeOutputStream True guarantees, that {@link OutputStream#close()}
 *   is called on the stream. False indicates, that only
 *   {@link OutputStream#flush()} should be called finally.
 * @param buffer Temporary buffer, which is to be used for
 *   copying data.
 * @return Number of bytes, which have been copied.
 * @throws IOException An I/O error occurred.
 */
public static long copy(InputStream inputStream, OutputStream outputStream, boolean closeOutputStream,
        byte[] buffer) throws IOException {
    OutputStream out = outputStream;
    InputStream in = inputStream;
    try {
        long total = 0;
        for (;;) {
            int res = in.read(buffer);
            if (res == -1) {
                break;
            }
            if (res > 0) {
                total += res;
                if (out != null) {
                    out.write(buffer, 0, res);
                }
            }
        }
        if (out != null) {
            if (closeOutputStream) {
                out.close();
            } else {
                out.flush();
            }
            out = null;
        }
        in.close();
        in = null;
        return total;
    } finally {
        IOUtils.closeQuietly(in);
        if (closeOutputStream) {
            IOUtils.closeQuietly(out);
        }
    }
}

From source file:com.mongolduu.android.ng.misc.HttpConnector.java

public static boolean downloadSong(long id, DownloadSongTask task) {
    try {//from   w  ww . j a v  a 2s  . com
        File file = Utils.getSongFile(id);
        if (file.exists()) {
            file.delete();
        }

        URL downloadURL = new URL(
                IMongolduuConstants.DOWNLOAD_URL + "?" + IMongolduuConstants.SONG_ID_PARAMETER_NAME + "=" + id);

        HttpClient httpClient = createHttpClient();
        HttpResponse httpResponse = httpClient.execute(new HttpGet(downloadURL.toURI()));
        HttpEntity httpEntity = httpResponse.getEntity();
        long length = 0;
        try {
            length = Long.parseLong(httpResponse.getHeaders("Content-Length")[0].getValue());
        } catch (NumberFormatException e) {
            Log.e(IMongolduuConstants.LOG_TAG, "exception", e);
        }

        InputStream input = new BufferedInputStream(httpEntity.getContent());
        OutputStream output = new FileOutputStream(file);
        byte buffer[] = new byte[1024];

        int count = 0;
        int total = 0;
        while ((count = input.read(buffer)) != -1 && !task.isCancelled()) {
            total += count;
            task.publishProgressFromOtherProcess((int) (total * 100 / length));
            output.write(buffer, 0, count);
        }
        output.flush();
        output.close();
        input.close();
        httpEntity.consumeContent();
        return true;
    } catch (Exception e) {
        Log.e(IMongolduuConstants.LOG_TAG, "exception", e);
    }
    return false;
}

From source file:info.icefilms.icestream.browse.Location.java

protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie,
        Callback callback) {/*  w w w.ja v  a2s .c  o  m*/
    // Declare our buffer
    ByteArrayBuffer byteArrayBuffer;

    try {
        // Setup the connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0");
        urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString());
        if (sendCookie != null)
            urlConnection.setRequestProperty("Cookie", sendCookie);
        if (sendData != null) {
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setDoOutput(true);
        }
        urlConnection.setConnectTimeout(callback.GetConnectionTimeout());
        urlConnection.setReadTimeout(callback.GetConnectionTimeout());
        urlConnection.connect();

        // Get the output stream and send the data
        if (sendData != null) {
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(sendData.getBytes());
            outputStream.flush();
            outputStream.close();
        }

        // Get the cookie
        if (getCookie != null) {
            // Clear the string builder
            getCookie.delete(0, getCookie.length());

            // Loop thru the header fields
            String headerName;
            String cookie;
            for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) {
                if (headerName.equalsIgnoreCase("Set-Cookie")) {
                    // Get the cookie
                    cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i));

                    // Add it to the string builder
                    if (cookie != null)
                        getCookie.append(cookie);

                    break;
                }
            }
        }

        // Get the input stream
        InputStream inputStream = urlConnection.getInputStream();

        // For some reason we can actually get a null InputStream instead of an exception
        if (inputStream == null) {
            Log.e("Ice Stream", "Page download failed. Unable to create Input Stream.");
            if (callback.GetErrorBoolean() == false) {
                callback.SetErrorBoolean(true);
                callback.SetErrorStringID(R.string.browse_page_download_error);
            }
            urlConnection.disconnect();
            return null;
        }

        // Get the file size
        final int fileSize = urlConnection.getContentLength();

        // Create our buffers
        byte[] byteBuffer = new byte[2048];
        byteArrayBuffer = new ByteArrayBuffer(2048);

        // Download the page
        int amountDownloaded = 0;
        int count;
        while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) {
            // Check if we got canceled
            if (callback.IsCancelled()) {
                inputStream.close();
                urlConnection.disconnect();
                return null;
            }

            // Add data to the buffer
            byteArrayBuffer.append(byteBuffer, 0, count);

            // Update the downloaded amount
            amountDownloaded += count;
        }

        // Close the connection
        inputStream.close();
        urlConnection.disconnect();

        // Check for amount downloaded calculation error
        if (fileSize != -1 && amountDownloaded != fileSize) {
            Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not "
                    + "match reported content length (" + fileSize + " bytes).");
        }
    } catch (SocketTimeoutException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_timeout_error);
        }
        return null;
    } catch (IOException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_download_error);
        }
        return null;
    }

    // Convert things to a string
    return new String(byteArrayBuffer.toByteArray());
}

From source file:com.dc.util.file.FileSupport.java

private static void copyEncryptedStream(InputStream input, OutputStream output, String key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    Cipher dcipher = Cipher.getInstance("AES");
    CipherInputStream cis = null;
    try {/*from   ww w .j a  v a2  s. c o  m*/
        dcipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        cis = new CipherInputStream(input, dcipher);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = cis.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
        output.flush();
    } finally {
        if (cis != null) {
            cis.close();
        }
    }
}