Example usage for java.io BufferedWriter flush

List of usage examples for java.io BufferedWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:m3umaker.exFiles.java

public void genFile(String M3UfileName, List Files) {
    try {// w w w.  j  ava  2 s  .  co m
        BufferedWriter out = new BufferedWriter(new FileWriter(mDIR + "\\" + M3UfileName + ".m3u", true));
        // System.out.println("----" + mDIR + M3UfileName);
        for (int i = 0; i < Files.size(); i++) {
            out.write(Files.get(i).toString());
            out.newLine();
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.zestedesavoir.zestwriter.model.Content.java

public void saveToMarkdown(File file) {
    DateFormat dateFormat = new SimpleDateFormat("dd MMMMM yyyy");
    StringBuilder sb = new StringBuilder();
    sb.append("% ").append(getTitle().toUpperCase()).append("\n");
    sb.append("% ").append(dateFormat.format(new Date())).append("\n\n");
    sb.append("# ").append(getIntroduction().getTitle()).append("\n\n");

    try (FileOutputStream fos = new FileOutputStream(file)) {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
        writer.append(sb.toString());/*from w  ww .j  a v a 2  s . com*/
        writer.append(exportContentToMarkdown(0, getDepth()));
        writer.flush();
    } catch (Exception e) {
        MainApp.getLogger().error(e.getMessage(), e);
    }
}

From source file:com.enioka.jqm.tools.MulticastPrintStream.java

private void write(String s, boolean newLine) {
    BufferedWriter textOut = logger.get();
    try {//  w w w.j ava 2  s .  c om
        ensureOpen();
        textOut.write(s);
        if (newLine) {
            textOut.newLine();
        }
        textOut.flush();
    } catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    } catch (IOException x) {
        // don't log exceptions, it could trigger a StackOverflow
    }
}

From source file:carskit.data.processor.DataTransformer.java

private void PublishNewRatingFiles(String outputfolder, Multimap<String, String> conditions,
        HashMap<String, HashMap<String, String>> newlines, boolean isLoose) throws Exception {
    // add missing values to the condition sets
    for (String dim : conditions.keySet()) {
        conditions.put(dim, "na");
    }/* ww  w  .j  a v a  2 s .co  m*/

    // create header
    StringBuilder headerBuilder = new StringBuilder();
    headerBuilder.append("user,item,rating");
    int start = 0;
    for (String dim : conditions.keySet()) {
        Collection<String> conds = conditions.get(dim);
        for (String cond : conds) {
            if (headerBuilder.length() > 0)
                headerBuilder.append(",");
            headerBuilder.append(dim + ":" + cond);
        }
    }
    String header = headerBuilder.toString();

    BufferedWriter bw = FileIO.getWriter(outputfolder + "ratings_binary.txt");
    bw.write(header + "\n");
    bw.flush();

    // start rewrite rating records
    for (String key : newlines.keySet()) {
        HashMap<String, String> ratingcontext = newlines.get(key);
        StringBuilder conditionBuilder = new StringBuilder();
        for (String dim : conditions.keySet()) {
            boolean isNA = false;
            boolean isCompleted = false;
            Collection<String> conds = conditions.get(dim);

            String dimCondition = ratingcontext.get(dim);
            if (dimCondition == null) {// 1st NA situation: because there is no such dim in this rating profile
                isNA = true;
            } else if (dimCondition.equals("na")) // 2nd NA situation: it is already tagged with NA in this dim
            {
                isNA = true;
            }

            for (String cond : conds) {
                if (conditionBuilder.length() > 0)
                    conditionBuilder.append(",");
                if (isLoose) {
                    if (isNA) {
                        if (cond.equals("na")) {
                            conditionBuilder.append("1");
                            isCompleted = true;
                        } else
                            conditionBuilder.append("0");
                    } else {
                        if (isCompleted)
                            conditionBuilder.append("0");
                        else {
                            if (cond.equals(dimCondition)) {
                                conditionBuilder.append("1");
                                isCompleted = true; // have found one condition for this dimension, all others are 0
                            } else
                                conditionBuilder.append("0");
                        }
                    }
                } else {
                    if (dimCondition.equals(cond))
                        conditionBuilder.append("1");
                    else
                        conditionBuilder.append("0");
                }
            }

        }
        String[] skey = key.split(",", -1); // when original format is compact, the key is whole line.
        if (skey.length > 3)
            key = skey[0].trim().toLowerCase() + "," + skey[1].trim().toLowerCase() + ","
                    + skey[2].trim().toLowerCase();

        bw.write(key + "," + conditionBuilder.toString() + "\n");
        bw.flush();
    }
    bw.close();
}

From source file:info.aamulumi.sharedshopping.network.RequestSender.java

/**
 * Send HTTP Request with params (x-url-encoded)
 *
 * @param requestURL     - URL of the request
 * @param method         - HTTP method (GET, POST, PUT, DELETE, ...)
 * @param urlParameters  - parameters send in URL
 * @param bodyParameters - parameters send in body (encoded)
 * @return JSONObject returned by the server
 *//*from ww w.java 2s .  co  m*/
public JSONObject makeHttpRequest(String requestURL, String method, HashMap<String, String> urlParameters,
        HashMap<String, String> bodyParameters) {
    HttpURLConnection connection = null;
    URL url;
    JSONObject jObj = null;

    try {
        // Check if we must add parameters in URL
        if (urlParameters != null) {
            String stringUrlParams = getFormattedParameters(urlParameters);
            url = new URL(requestURL + "?" + stringUrlParams);
        } else
            url = new URL(requestURL);

        // Create connection
        connection = (HttpURLConnection) url.openConnection();

        // Add cookies to request
        if (mCookieManager.getCookieStore().getCookies().size() > 0)
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", mCookieManager.getCookieStore().getCookies()));

        // Set request parameters
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod(method);
        connection.setDoInput(true);

        // Check if we must add parameters in body
        if (bodyParameters != null) {
            // Create a string with parameters
            String stringBodyParameters = getFormattedParameters(bodyParameters);

            // Set output request parameters
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length",
                    "" + Integer.toString(stringBodyParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "fr-FR");

            // Send body's request
            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(stringBodyParameters);

            writer.flush();
            writer.close();
            os.close();
        }

        // Get response code
        int responseCode = connection.getResponseCode();

        // If response is 200 (OK)
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            // Keep new cookies in the manager
            List<String> cookiesHeader = connection.getHeaderFields().get(COOKIES_HEADER);
            if (cookiesHeader != null) {
                for (String cookie : cookiesHeader)
                    mCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
            }

            // Read the response
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();

            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }

            // Parse the response to a JSON Object
            try {
                jObj = new JSONObject(sb.toString());
            } catch (JSONException e) {
                Log.d("JSON Parser", "Error parsing data " + e.toString());
                Log.d("JSON Parser", "Setting value of jObj to null");
                jObj = null;
            }
        } else {
            Log.w("HttpUrlConnection", "Error : server sent code : " + responseCode);
        }
    } catch (MalformedURLException e) {
        Log.e("Network", "Error in URL");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Close connection
        if (connection != null)
            connection.disconnect();
    }

    return jObj;
}

From source file:com.mabi87.httprequestbuilder.HTTPRequest.java

/**
 * @throws IOException/* ww w.j ava 2  s .c  o m*/
 *             throws from HttpURLConnection method.
 * @return the HTTPResponse object
 */
private HTTPResponse post() throws IOException {
    URL url = new URL(mPath);
    HttpURLConnection lConnection = (HttpURLConnection) url.openConnection();

    lConnection.setReadTimeout(mReadTimeoutMillis);
    lConnection.setConnectTimeout(mConnectTimeoutMillis);
    lConnection.setRequestMethod("POST");
    lConnection.setDoInput(true);
    lConnection.setDoOutput(true);

    OutputStream lOutStream = lConnection.getOutputStream();
    BufferedWriter lWriter = new BufferedWriter(new OutputStreamWriter(lOutStream, "UTF-8"));
    lWriter.write(getQuery(mParameters));
    lWriter.flush();
    lWriter.close();
    lOutStream.close();

    HTTPResponse response = readPage(lConnection);

    return response;
}

From source file:playground.christoph.evacuation.analysis.AgentsInEvacuationAreaWriter.java

/**
 * Writes the gathered data tab-separated into a text file.
 *
 * @param filename The name of a file where to write the gathered data.
 *//*  w  ww  .java 2 s . c  om*/
public void write(final String filename, int[] activities, Map<String, int[]> legs) {

    try {
        BufferedWriter bufferedWriter = IOUtils.getBufferedWriter(filename);
        write(bufferedWriter, activities, legs);
        bufferedWriter.flush();
        bufferedWriter.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.ucsd.crbs.cws.io.ResourceToExecutableScriptWriterImpl.java

/**
 * Writes a given resource to an executable script file.  The result is written to
 * <b>destinationScript</b> and this script is made executable via File setExecutable
 * method.//from   ww  w .  j  av  a 2 s . c  om
 * 
 * @param resourcePath Path that can be loaded via {@link Class.class.getResourceAsStream} 
 * @param destinationScript File to write script to
 * @param replacer Optional object that lets caller alter script on a line by line basis before it is written
 * @throws Exception if there is an io error
 * @throws IllegalArgumentException if either <b>resourcePath</b> or <b>destinationScript</b> are null
 */
@Override
public void writeResourceToScript(final String resourcePath, final String destinationScript,
        StringReplacer replacer) throws Exception {
    if (resourcePath == null) {
        throw new IllegalArgumentException("resourcePath method parameter cannot be null");
    }

    if (destinationScript == null) {
        throw new IllegalArgumentException("destinationScript method parameter cannot be null");
    }

    //load script
    List<String> scriptLines = IOUtils.readLines(Class.class.getResourceAsStream(resourcePath));

    BufferedWriter bw = new BufferedWriter(new FileWriter(destinationScript));

    for (String line : scriptLines) {
        if (replacer != null) {
            bw.write(replacer.replace(line));
        } else {
            bw.write(line);
        }
        bw.newLine();
    }
    bw.flush();
    bw.close();

    //make script executable
    File script = new File(destinationScript);
    script.setExecutable(true, false);

}

From source file:com.enioka.jqm.tools.MultiplexPrintStream.java

private void write(String s, boolean newLine) {
    BufferedWriter textOut = logger.get();
    try {// w  w  w  .  j  ava2  s .  co  m
        ensureOpen();
        textOut.write(s);
        if (newLine) {
            textOut.newLine();
        }
        textOut.flush();

        if (useCommonLogFile && textOut != original) {
            alljobslogger.info(s + (newLine ? ls : ""));
        }
    } catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    } catch (IOException x) {
        // don't log exceptions, it could trigger a StackOverflow
    }
}

From source file:com.codemage.sql.util.SonarQubeManager.java

public void createJavaFile(String JavaCode) {
    BufferedWriter bw = null;

    try {/*from  ww w  .j a v  a  2  s  .  c o  m*/
        // APPEND MODE SET HERE
        bw = new BufferedWriter(new FileWriter(
                "E:\\Smile24\\Projects\\0005 - CAL\\sampleAnalyseCode\\src\\main\\java\\checkbook.java",
                false));
        bw.write(JavaCode);
        bw.newLine();
        bw.flush();
    } catch (IOException ioe) {
    } finally { // always close the file
        if (bw != null) {
            try {
                bw.close();
            } catch (IOException ioe2) {
                // just ignore it
            }
        }
    } // end try/catch/finally
}