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.alteiar.utils.file.SerializableFile.java

/**
 * /*from  w  w  w.  j a va  2  s .c om*/
 * @param data
 * @param dest
 *            - the file must exist
 * @throws IOException
 */
private static void writeByteToFile(byte[] data, File dest) throws IOException {
    OutputStream os = null;

    IOException ex = null;

    try {
        os = new FileOutputStream(dest);
        os.write(data);
        os.flush();
    } catch (IOException e) {
        ex = e;
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            ex = e;
        }
    }

    if (ex != null) {
        throw ex;
    }
}

From source file:ReadTemp.java

/** Executes the given applescript code and returns the first line of the 
 output as a string *///from ww w. j av  a 2s  .c o m
static String doApplescript(String script) {
    String line;
    try {
        // Start applescript 
        Process p = Runtime.getRuntime().exec("/usr/bin/osascript -s o -");

        // Send applescript via stdin
        OutputStream stdin = p.getOutputStream();
        stdin.write(script.getBytes());
        stdin.flush();
        stdin.close();

        // get first line of output
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        line = input.readLine();
        input.close();

        // If we get an exit code, print it out
        if (p.waitFor() != 0) {
            System.err.println("exit value = " + p.exitValue());
            System.err.println(line);
        }
        return line;
    } catch (Exception e) {
        System.err.println(e);
    }

    return "";
}

From source file:Main.java

public static String executePost(String targetURL, String urlParameters) {
    try {/*from   w ww  .  j  ava 2 s .c  om*/
        HttpURLConnection connection = (HttpURLConnection) new URL(targetURL).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        //connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(urlParameters.getBytes());
        } finally {
            if (output != null)
                try {
                    output.flush();
                    output.close();
                } catch (IOException logOrIgnore) {
                }
        }
        InputStream response = connection.getInputStream();
        String contentType = connection.getHeaderField("Content-Type");
        String responseStr = "";
        if (true) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(response));
                for (String line; (line = reader.readLine()) != null;) {
                    //System.out.println(line);
                    responseStr = responseStr + line;
                    Thread.sleep(2);
                }
            } finally {
                if (reader != null)
                    try {
                        reader.close();
                    } catch (IOException logOrIgnore) {
                    }
            }
        } else {
            // It's likely binary content, use InputStream/OutputStream.
            System.out.println("Binary content");
        }
        return responseStr;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:de.thischwa.pmcms.tool.compression.Zip.java

/**
 * Method to extract all {@link ZipInfo}s into 'destDir'. Inner directory structure will be copied.
 * /* w w w. ja  v  a2s  . c  o m*/
 * @param destDir
 * @param zipInfo
 * @param monitor must be initialized by the caller.
 * @throws IOException
 */
public static void extract(final File destDir, final ZipInfo zipInfo, final IProgressMonitor monitor)
        throws IOException {
    if (!destDir.exists())
        destDir.mkdirs();

    for (String key : zipInfo.getEntryKeys()) {
        ZipEntry entry = zipInfo.getEntry(key);
        InputStream in = zipInfo.getInputStream(entry);
        File entryDest = new File(destDir, entry.getName());
        entryDest.getParentFile().mkdirs();
        if (!entry.isDirectory()) {
            OutputStream out = new FileOutputStream(new File(destDir, entry.getName()));
            try {
                IOUtils.copy(in, out);
                out.flush();
                if (monitor != null)
                    monitor.worked(1);
            } finally { // cleanup
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }
        }
    }
    if (monitor != null)
        monitor.done();
}

From source file:Main.java

/** Write a DOM document to an OutputStream */
public static void writeXmlDocumentToStream(Document document, OutputStream stream) throws Exception {
    Source source = new DOMSource(document);
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    StreamResult result = new StreamResult(stream);
    transformer.transform(source, result);
    stream.flush();
}

From source file:com.adanac.module.blog.api.HttpApiHelper.java

public static void baiduPush(int remain) {
    String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl();
    if (pushUrl == null) {
        if (logger.isInfoEnabled()) {
            logger.info("all html page has been pushed!");
        }//from  w w w  . j ava  2s  .  co  m
        return;
    }
    if (remain <= 0) {
        if (logger.isInfoEnabled()) {
            logger.info("there has no remain[" + remain + "]!");
        }
        return;
    }
    if (logger.isInfoEnabled()) {
        logger.info("find push url : " + pushUrl);
    }
    String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token;
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(pushUrl.getBytes("UTF-8"));
        outputStream.write("\r\n".getBytes("UTF-8"));
        outputStream.flush();
        int status = connection.getResponseCode();
        if (logger.isInfoEnabled()) {
            logger.info("baidu-push response code : " + status);
        }
        if (status == HttpServletResponse.SC_OK) {
            String response = IOUtil.read(connection.getInputStream());
            if (logger.isInfoEnabled()) {
                logger.info("baidu-push response : " + response);
            }
            JSONObject result = JSONObject.fromObject(response);
            if (result.getInt("success") >= 1) {
                DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl);
            } else {
                logger.warn("push url failed : " + pushUrl);
            }
            baiduPush(result.getInt("remain"));
        } else {
            logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream()));
        }
    } catch (Exception e) {
        logger.error("baidu push failed ...", e);
    }
}

From source file:Main.java

public static File writeFromInput(String path, String fileName, InputStream is) {
    File file = createFile(path, fileName);

    OutputStream os = null;
    try {/*from  w w  w  . j  a  v  a2 s .co  m*/
        os = new FileOutputStream(file);
        byte[] buffer = new byte[4 * 1024];
        int read = 0;
        while ((read = is.read(buffer)) != -1) {
            os.write(buffer, 0, read);
        }
        os.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file;
}

From source file:cn.isif.util_plus.http.client.multipart.HttpMultipart.java

private static void writeBytes(final ByteArrayBuffer b, final OutputStream out) throws IOException {
    out.write(b.buffer(), 0, b.length());
    out.flush();
}

From source file:com.fluidops.iwb.cms.util.IWBCmsUtil.java

public static File upload(String filename, Resource subject, InputStream is, Collector collector)
        throws FileNotFoundException, IOException {
    if (Config.getConfig().uploadFileClass().equals(LocalFile.class.getName()))
        GenUtil.mkdirs(IWBFileUtil.getUploadFolder());

    File file = uploadedFileFor(filename);
    if (file.exists())
        throw new IllegalStateException("Error during upload: File " + filename + " already exists.");

    ReadWriteDataManager dm = null;// www.  jav a2  s . c om
    try {
        dm = ReadWriteDataManagerImpl.openDataManager(Global.repository);

        OutputStream out = file.getOutputStream();
        out.write(GenUtil.readUrlToBuffer(is).toByteArray());
        out.flush();
        out.close();

        // if we have a page subject, write triple (subject, hasFile, file)
        ValueFactory vf = ValueFactoryImpl.getInstance();
        Context c = Context.getFreshUserContextWithURI(getFileContextURI(file), ContextLabel.FILE_UPLOAD);
        c.setEditable(false);

        if (subject != null)
            dm.addToContext(vf.createStatement(subject, Vocabulary.SYSTEM.ATTACHEDFILE, file.getURI()), c);

        dm.addToContext(collector.collectRDF(file, file.getURI()), c);

        return file;
    } finally {
        ReadWriteDataManagerImpl.closeQuietly(dm);
    }
}

From source file:Main.java

static public boolean copyFileTo(Context c, String orifile, String desfile) throws IOException {
    InputStream myInput;/*  w  ww  . j a  va2 s.com*/
    OutputStream myOutput = new FileOutputStream(desfile);
    myInput = c.getAssets().open(orifile);
    byte[] buffer = new byte[1024];
    int length = myInput.read(buffer);
    while (length > 0) {
        myOutput.write(buffer, 0, length);
        length = myInput.read(buffer);
    }

    myOutput.flush();
    myInput.close();
    myOutput.close();

    return true;
}