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:SDRecord.java

private static long recordToFile(DatagramPacket packet, OutputStream writer) {
    try {/*from w w w.  j a  v a 2  s.  co  m*/
        writer.write(packet.getData(), 0, packet.getLength());
        writer.flush();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(5);
    }
    return packet.getLength();
}

From source file:gridool.util.net.SocketUtils.java

public static boolean write(final Socket socket, final byte[] b, final long delay, final int maxRetry)
        throws IOException {
    final OutputStream sockout = socket.getOutputStream();
    for (int i = 0; i < maxRetry; i++) {
        try {/* ww w.  j a  va2 s  .  c  om*/
            sockout.write(b);
            sockout.flush();
            return true;
        } catch (IOException e) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Failed to write to socket: " + socket.getRemoteSocketAddress() + " #" + i);
            }
        }
        if (delay > 0) {
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ie) {
                ;
            }
        }
    }
    if (LOG.isWarnEnabled()) {
        LOG.warn("Failed to write to socket: " + socket.getRemoteSocketAddress());
    }
    return false;
}

From source file:io.cloudslang.content.vmware.utils.OvfUtils.java

public static long writeToStream(OutputStream outputStream, ProgressUpdater progressUpdater, long bytesCopied,
        byte[] buffer, int read) throws Exception {
    outputStream.write(buffer, 0, read);
    outputStream.flush();
    bytesCopied += read;/*from  w  w  w .  j a v a  2  s . co m*/
    progressUpdater.updateBytesSent(read);
    return bytesCopied;
}

From source file:models.logic.CipherDecipher.java

public static void doCopy(InputStream is, OutputStream os) throws IOException {
    byte[] bytes = new byte[64];
    int numBytes;
    while ((numBytes = is.read(bytes)) != -1) {
        os.write(bytes, 0, numBytes);//from w w  w . ja va  2s  .  co  m
    }
    os.flush();
    os.close();
    is.close();
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * //from w w  w.  j a v  a 2  s. c  o  m
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:Main.java

public static void writeNumber(OutputStream out, long s, int len, boolean big_endian) throws IOException {
    if (len <= 0 || len > 8)
        throw new IllegalArgumentException("length must between 1 and 8.");

    byte[] buffer = numberToBytes(s, len, big_endian);
    out.write(buffer);/*from   w  ww  . j  a v  a 2 s. c  o  m*/
    out.flush();
}

From source file:Main.java

public static void saveBitmap2file(Bitmap bmp, File file) {

    OutputStream stream = null;
    try {//from w w  w  .j  a  v  a 2s  .  c o m
        stream = new FileOutputStream(file.getAbsolutePath());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);

    try {
        stream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:Main.java

public static void copyStream(InputStream is, OutputStream os) {
    try {/* www  . j  av a  2s  .co  m*/
        final byte[] bytes = new byte[BUFFER_SIZE];

        int count = is.read(bytes, 0, BUFFER_SIZE);
        while (count > -1) {
            os.write(bytes, 0, count);
            count = is.read(bytes, 0, BUFFER_SIZE);
        }

        os.flush();
    } catch (Exception ex) {
        Log.e("", "", ex);
    }
}

From source file:Main.java

public static long getFirstInstalled() {
    long firstInstalled = 0;
    PackageManager pm = myApp.getPackageManager();
    try {// ww w  .  j a  va2  s. c  om
        PackageInfo pi = pm.getPackageInfo(myApp.getApplicationContext().getPackageName(), pm.GET_SIGNATURES);
        try {
            try {
                //noinspection AndroidLintNewApi
                firstInstalled = pi.firstInstallTime;
            } catch (NoSuchFieldError e) {
            }
        } catch (Exception ee) {
        }
        if (firstInstalled == 0) { // old versions of Android don't have firstInstallTime in PackageInfo
            File dir;
            try {
                dir = new File(
                        getApp().getApplicationContext().getExternalCacheDir().getAbsolutePath() + "/.config");
            } catch (Exception e) {
                dir = null;
            }
            if (dir != null && (dir.exists() || dir.mkdirs())) {
                File fTimeStamp = new File(dir.getAbsolutePath() + "/.myconfig");
                if (fTimeStamp.exists()) {
                    firstInstalled = fTimeStamp.lastModified();
                } else {
                    // create this file - to make it slightly more confusing, write the signature there
                    OutputStream out;
                    try {
                        out = new FileOutputStream(fTimeStamp);
                        out.write(pi.signatures[0].toByteArray());
                        out.flush();
                        out.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
    }
    return firstInstalled;
}

From source file:big.zip.java

/**
 * When given a zip file, this method will open it up and extract all files
 * inside into a specific folder on disk. Typically on BIG archives, the zip
 * file only contains a single file with the original file name.
 * @param fileZip           The zip file that we want to extract files from
 * @param folderToExtract   The folder where the extract file will be placed 
 * @return True if no problems occurred, false otherwise
 *//*from   ww w . ja  v  a2  s.  c  o m*/
public static boolean extract(final File fileZip, final File folderToExtract) {
    // preflight check
    if (fileZip.exists() == false) {
        System.out.println("ZIP126 - Zip file not found: " + fileZip.getAbsolutePath());
        return false;
    }
    // now proceed to extract the files
    try {
        final InputStream inputStream = new FileInputStream(fileZip);
        final ArchiveInputStream ArchiveStream;
        ArchiveStream = new ArchiveStreamFactory().createArchiveInputStream("zip", inputStream);
        final ZipArchiveEntry entry = (ZipArchiveEntry) ArchiveStream.getNextEntry();
        final OutputStream outputStream = new FileOutputStream(new File(folderToExtract, entry.getName()));
        IOUtils.copy(ArchiveStream, outputStream);

        // flush and close all files
        outputStream.flush();
        outputStream.close();
        ArchiveStream.close();
        inputStream.close();
    } catch (ArchiveException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(zip.class.getName()).log(Level.SEVERE, null, ex);
    }
    return true;
}