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:edu.iu.daal_kmeans.regroupallgather.KMUtil.java

/**
 * Generate centroids and upload to the cDir
 * /*from  ww  w  . ja  va  2  s  . c  om*/
 * @param numCentroids
 * @param vectorSize
 * @param configuration
 * @param random
 * @param cenDir
 * @param fs
 * @throws IOException
 */
static void generateCentroids(int numCentroids, int vectorSize, Configuration configuration, Path cenDir,
        FileSystem fs) throws IOException {
    Random random = new Random();
    double[] data = null;
    if (fs.exists(cenDir))
        fs.delete(cenDir, true);
    if (!fs.mkdirs(cenDir)) {
        throw new IOException("Mkdirs failed to create " + cenDir.toString());
    }
    data = new double[numCentroids * vectorSize];
    for (int i = 0; i < data.length; i++) {
        data[i] = random.nextDouble() * 1000;
    }
    Path initClustersFile = new Path(cenDir, Constants.CENTROID_FILE_NAME);
    System.out.println("Generate centroid data." + initClustersFile.toString());
    FSDataOutputStream out = fs.create(initClustersFile, true);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
    for (int i = 0; i < data.length; i++) {
        if ((i % vectorSize) == (vectorSize - 1)) {
            bw.write(data[i] + "");
            bw.newLine();
        } else {
            bw.write(data[i] + " ");
        }
    }
    bw.flush();
    bw.close();
    System.out.println("Wrote centroids data to file");
}

From source file:io.jari.geenstijl.API.API.java

public static String postUrl(String url, List<NameValuePair> params, String cheader, boolean refererandorigin)
        throws IOException {
    HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
    http.setRequestMethod("POST");
    http.setDoInput(true);//from   www .  j a va2  s. com
    http.setDoOutput(true);
    if (cheader != null)
        http.setRequestProperty("Cookie", cheader);
    if (refererandorigin) {
        http.setRequestProperty("Referer",
                "http://www.geenstijl.nl/mt/archieven/2014/01/brein_chanteert_ondertitelaars.html");
        http.setRequestProperty("Origin", "http://www.geenstijl.nl");
    }
    OutputStream os = http.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();

    http.connect();

    InputStream in = http.getInputStream();
    String encoding = http.getContentEncoding();
    encoding = encoding == null ? "UTF-8" : encoding;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    int len = 0;
    while ((len = in.read(buf)) != -1) {
        baos.write(buf, 0, len);
    }
    return new String(baos.toByteArray(), encoding);
}

From source file:com.thejustdo.util.Utils.java

/**
 * Creates a new temporal file with the content given in the string.
 * @param content What to write son of a bitch.
 *///  w ww.  j  a v a 2 s  .  c  o m
public static void createTMPFile(String content, File goal) throws IOException {
    // 1. Creating the writers.
    FileOutputStream fos = new FileOutputStream(goal);
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "ISO-8859-1"));

    // 2. Writing contents.
    writer.write(content);

    // 3. Closing stream.
    writer.flush();
    writer.close();
    fos.close();
}

From source file:at.riemers.velocity2js.velocity.Velocity2Js.java

public static void generateDir(String templateDir, String javascriptDir, List<I18NBundle> bundles)
        throws Exception {

    Properties p = new Properties();
    p.setProperty("resource.loader", "file");

    p.setProperty("file.resource.loader.description", "Velocity File Resource Loader");
    p.setProperty("file.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.FileResourceLoader");

    p.setProperty("file.resource.loader.path", templateDir);
    Velocity2Js.init(p);/*www . ja v a2s  .  c o  m*/

    File tDir = new File(templateDir);

    for (I18NBundle bundle : bundles) {
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(javascriptDir + "/vel2js" + bundle.getLocale() + ".js"), "UTF8"));

        //BufferedWriter out = new BufferedWriter(new FileWriter(new File(javascriptDir + "/vel2js" + bundle.getLocale() + ".js")));
        process(tDir, null, out, bundle.getBundle());
        out.flush();
        out.close();
    }

}

From source file:application.gen.gen.java

public static void gen(VelocityContext context, String templateFile, String genFilePath) {
    try {/*from  w  ww . j  a  va 2s . c  o  m*/
        Template template = null;
        try {
            template = Velocity.getTemplate(templateFile);

        } catch (ResourceNotFoundException rnfe) {
            System.out.println("Example : error : cannot find template " + templateFile);
        } catch (ParseErrorException pee) {
            System.out.println("Example : Syntax error in template " + templateFile + ":" + pee);
        }

        // BufferedWriter writer = new BufferedWriter(new
        // OutputStreamWriter(System.out));
        StringWriter ww = new StringWriter();
        BufferedWriter writer = new BufferedWriter(ww);
        if (template != null)
            template.merge(context, ww);
        // System.out.println(ww.toString());
        FileUtils.writeStringToFile(new File(genFilePath), ww.toString(), "utf-8");
        System.out.println("generate file" + genFilePath);
        /*
         * flush and cleanup
         */
        writer.flush();
        writer.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:net.duckling.ddl.util.FileUtil.java

/**
 * Brief Intro Here//from  w w  w .ja  v  a  2  s  . co  m
 * @param file ?
 * @param content ?
 * @param charset ?
 * @return ??
 */
public static boolean writeFile(File file, String content, String charset) {
    try {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
        bw.write(content);
        bw.flush();
        bw.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) {

    URL sendUrl;//w ww  .  ja  v a 2s.  com
    try {
        sendUrl = new URL(url);
    } catch (MalformedURLException e) {
        Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL");
        return null;
    }

    HttpURLConnection conn = null;

    try {
        conn = (HttpURLConnection) sendUrl.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(1024);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + "");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        //writer.write(getPostDataStringfromJsonObject(jsonObjSend));
        Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString());
        //writer.write(jsonObjSend.toString());
        writer.write(String.valueOf(jsonObjSend));

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

        int responseCode = conn.getResponseCode();
        Log.d(TAG, "responseCode = " + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            Log.d(TAG, "responseCode = HTTP OK");

            InputStream instream = conn.getInputStream();

            String resultString = convertStreamToString(instream);
            instream.close();
            Log.d(TAG, "resultString = " + resultString);
            //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;

        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return null;

}

From source file:de.fau.amos.FileDownload.java

/**
 * Creates a .csv file containing the data of the passed "ArrayList<ArrayList<String>> data" and saves it into the "userdir.location" directory
 * @param data// w w  w .  j av  a  2  s  .  co m
 * @param fileName
 */
private static void createCsvFile(ArrayList<ArrayList<String>> data, String fileName) {

    try {
        String lines = "";

        //using Buffered Writer to write a file into the "userdir.location" directory
        BufferedWriter bw = new BufferedWriter(
                new FileWriter(new File(System.getProperty("userdir.location"), fileName)));

        //every single value will be written down into the file separated by a semicolon
        for (int i = 0; i < data.size(); i++) {
            for (int j = 0; j < data.get(i).size(); j++) {
                lines = data.get(i).get(j) + "; ";
                bw.write(lines);
            }
            bw.newLine();

        }
        bw.flush();
        bw.close();

        System.out.println("Success!");
    } catch (IOException e) {
        System.out.println("Couldn't create File!");
    }
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;/*from   ww w.  ja  va2  s .  c om*/
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.connect();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:com.axelor.apps.tool.file.FileTool.java

/**
 * Mthode permettant d'crire plusieurs lignes dans un fichier
 * @param destinationFolder//w  w  w .jav a  2s.c o  m
 *             Le chemin du fichier
 * @param fileName
 *             Le nom du fichier
 * @param line
 *             La liste de ligne  crire
 * @throws IOException
 */
public static void writer(String destinationFolder, String fileName, List<String> multiLine)
        throws IOException {
    System.setProperty("line.separator", "\r\n");
    BufferedWriter output = null;
    try {

        File file = create(destinationFolder, fileName);
        output = new BufferedWriter(new FileWriter(file));
        int i = 0;

        for (String line : multiLine) {

            output.write(line);
            output.newLine();
            i++;
            if (i % 50 == 0) {
                output.flush();
            }

        }

    } catch (IOException ex) {

        LOG.error(ex.getMessage());

    } finally {

        if (output != null) {
            output.close();
        }
    }
}