Example usage for java.io BufferedWriter write

List of usage examples for java.io BufferedWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

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

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

    URL sendUrl;/*from w  ww  .ja va2 s.  c o m*/
    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:com.github.braully.graph.DatabaseFacade.java

private static String saveConsole(List<String> consoleOut, String fileGraphName) {
    if (consoleOut == null || consoleOut.isEmpty()) {
        return null;
    }// ww w .  j av a 2  s.  c  om
    String fileName = fileGraphName;

    char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    StringBuilder sb = new StringBuilder();
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        char c = chars[random.nextInt(chars.length)];
        sb.append(c);
    }

    fileName = fileGraphName + ".log";
    File fileOut = new File(DATABASE_DIRECTORY_GRAPH + File.separator + fileName);
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(fileOut));
        for (String l : consoleOut) {
            bw.write(l);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileName;
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

/**
 * Puts results into a HTML file.//from ww  w  . j  ava 2 s .  co m
 *
 * @param prefix
 * @param hits
 * @param reader
 * @param queryImage
 * @return
 * @throws IOException
 */
public static String saveImageResultsToHtml(String prefix, TopDocs hits, IndexReader reader, String queryImage)
        throws IOException {
    long l = System.currentTimeMillis() / 1000;
    String fileName = "results-" + prefix + "-" + l + ".html";
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    bw.write("<html>\n" + "<head><title>Search Results</title></head>\n" + "<body bgcolor=\"#FFFFFF\">\n");
    bw.write("<h3>query</h3>\n");
    bw.write("<a href=\"file://" + queryImage + "\"><img src=\"file://" + queryImage + "\"></a><p>\n");
    bw.write("<h3>results</h3>\n");
    for (int i = 0; i < hits.scoreDocs.length; i++) {
        bw.write(hits.scoreDocs[i].score + " - <a href=\"file://"
                + reader.document(hits.scoreDocs[i].doc).get("descriptorImageIdentifier")
                + "\"><img src=\"file://"
                + reader.document(hits.scoreDocs[i].doc).get("descriptorImageIdentifier") + "\"></a><p>\n");
    }
    bw.write("</body>\n" + "</html>");
    bw.close();
    return fileName;
}

From source file:net.semanticmetadata.lire.utils.FileUtils.java

/**
 * Puts results into a HTML file./*from   www  .j  ava  2 s. c om*/
 *
 * @param prefix
 * @param hits
 * @param queryImage
 * @return
 * @throws IOException
 */
public static String saveImageResultsToHtml(String prefix, ImageSearchHits hits, String queryImage,
        IndexReader reader) throws IOException {
    long l = System.currentTimeMillis() / 1000;
    String fileName = "results-" + prefix + "-" + l + ".html";
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    bw.write("<html>\n" + "<head><title>Search Results</title></head>\n" + "<body bgcolor=\"#FFFFFF\">\n");
    bw.write("<h3>query</h3>\n");
    bw.write("<a href=\"file://" + queryImage + "\"><img src=\"file://" + queryImage + "\"></a><p>\n");
    bw.write("<h3>results</h3>\n");
    for (int i = 0; i < hits.length(); i++) {
        bw.write(hits.score(i) + " - <a href=\"file://"
                + reader.document(hits.documentID(i)).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]
                + "\"><img src=\"file://"
                + reader.document(hits.documentID(i)).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]
                + "\"></a><p>\n");
    }
    bw.write("</body>\n" + "</html>");
    bw.close();
    return fileName;
}

From source file:adalid.commons.velocity.VelocityEngineer.java

public static void write(VelocityContext context, String tempname, String filename, String charset1,
        String charset2) throws Exception {
    charset1 = StringUtils.defaultIfBlank(charset1, getTemplateEncoding(tempname));
    charset2 = StringUtils.defaultIfBlank(charset2, getDocumentEncoding(filename));
    //      if (!charset1.equals(VELOCITY_TEMPLATE_DEFAULT_ENCODING)) {
    //          log(Level.INFO, "write", "template=" + tempname, "template-encoding=" + charset1, "document-encoding=" + charset2);
    //      }/*  w w  w .ja v  a2  s.c  om*/
    //      if (!charset1.equals(charset2)) {
    //          log(Level.WARN, "write", "template=" + tempname, "template-encoding=" + charset1, "document-encoding=" + charset2);
    //      }
    StringWriter sw = merge(context, tempname, charset1);
    if (sw != null) {
        FileOutputStream fileOutputStream;
        OutputStreamWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileOutputStream = new FileOutputStream(filename);
            fileWriter = new OutputStreamWriter(fileOutputStream, charset2);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(sw.toString());
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException ex) {
                    logger.fatal(ThrowableUtils.getString(ex), ex);
                }
            }
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException ex) {
                    logger.fatal(ThrowableUtils.getString(ex), ex);
                }
            }
        }
    }
}

From source file:gamlss.utilities.MatrixFunctions.java

/**
 * Write vector values to CSV file./*from   w w  w . j  av  a  2s .  c  o  m*/
 * @param cmd - path to the file
 * @param v - vector to write
 */
public static void vectorWriteCSV(final String cmd, final RealVector v, boolean append) {
    try {
        // Create file 
        FileWriter fstream = new FileWriter(cmd, append);
        BufferedWriter out = new BufferedWriter(fstream);

        for (int j = 0; j < v.getDimension(); j++) {
            out.write(Double.toString(v.getEntry(j)));
            out.newLine();
        }
        out.close();
    } catch (Exception e) { //Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }
}

From source file:org.opentides.util.FileUtil.java

/**
 * Helper class to write specified content to certain file.
 * //from  w  ww.j av  a 2s.c  om
 * @param filename
 * @param content
 * @return true if writing is successful
 */
public static void writeFile(String filename, String content) {
    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new FileWriter(filename));
        writer.write(content);
        writer.close();
    } catch (IOException ioe) {
        String msg = "Cannot access file [" + filename + "].";
        _log.error(ioe, ioe);
        throw new InvalidImplementationException(msg, ioe);
    }
}

From source file:atg.tools.dynunit.test.util.FileUtil.java

/**
 * @see #forceGlobalScope(java.io.File)//w  w w .j  av a  2s .  c  o m
 * @see #forceComponentScope(java.io.File, String)
 */
@Deprecated
public static void searchAndReplace(@NotNull final String originalValue, @NotNull final String newValue,
        @NotNull final File file) throws IOException {
    final File tempFile = newTempFile();

    if (CONFIG_FILES_GLOBAL_FORCE != null && CONFIG_FILES_GLOBAL_FORCE.get(file.getPath()) != null
            && CONFIG_FILES_GLOBAL_FORCE.get(file.getPath()) == file.lastModified() && file.exists()) {
        dirty = false;
        logger.debug(
                "{} last modified hasn't changed and file still exists, " + "no need for global scope force",
                file.getPath());
    } else {
        final BufferedWriter out = new BufferedWriter(new FileWriter(tempFile));
        final BufferedReader in = new BufferedReader(new FileReader(file));
        String str;
        while ((str = in.readLine()) != null) {
            if (str.contains(originalValue)) {
                out.write(newValue);
            } else {
                out.write(str);
                out.newLine();
            }
        }
        out.close();
        in.close();
        JarUtils.copy(tempFile, file, true, false);
        CONFIG_FILES_GLOBAL_FORCE.put(file.getPath(), file.lastModified());
        dirty = true;
    }

}

From source file:com.aurel.track.lucene.util.FileUtil.java

public static void write(File file, String s, boolean lazy) throws IOException {

    if (file.getParent() != null) {
        mkdirs(file.getParent());/*from w  w  w. java2s .  c  o  m*/
    }

    if (file.exists()) {
        String content = FileUtil.read(file);

        if (content.equals(s)) {
            return;
        }
    }

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

    bw.flush();
    bw.write(s);

    bw.close();
}

From source file:com.hp.test.framework.Utlis.java

public static void replaceMainTable(Boolean onlyMainTable, File f) {

    String content = "";
    String content1 = "";
    String replace = "";
    String imagePath = "../../../../../../../";
    if (f.getName().contentEquals("index.html")) {
        imagePath = "";
    }//from  ww  w. j  ava  2s  . c  o m

    if (f.getName().contentEquals("ConsolidatedPage.html")) {
        imagePath = "../";
    }

    if (f.getName().contentEquals("index.html")) {
        imagePath = "";
    }

    if (f.getName().contentEquals("CurrentRun.html")) {
        imagePath = "../../";
    }

    replace = "<tr id=\"header\" >" + "\n";
    replace = replace + "<td id=\"logo\"><img src=\"" + imagePath
            + "HTML_Design_Files/IMG/Framework_Logo.jpg\" alt=\"Logo\" height=\"70\" width=\"140\" /> <br/><i style=\"float:left;padding-left:20px;font-size:12px\">Reflections of Visionary Minds</i></td>";
    replace = replace + " <td id=\"headertext\">";
    replace = replace + "Intelligent Solutions Test Framework";
    replace = replace + "<div style=\"padding-right:20px;float:right\"><img src=\"" + imagePath
            + "HTML_Design_Files/IMG/hp.png\" height=\"70\" width=\"140\" /> </i></div>                </td>";
    replace = replace + " </tr>";

    try {
        BufferedReader in = new BufferedReader(new FileReader(f));

        String str;
        Boolean found = false;
        boolean readingdone = false;
        while ((str = in.readLine()) != null) {
            //      System.out.println(""+str);
            content1 += str;
            if (!onlyMainTable) {
                if (str.contains("<td id=\"content\">")) {

                    content1 += " <img src=\"HTML_Design_Files\\\\IMG\\reports.jpg\"  alt=\"BackGround\" height=\"500\" width=\"500\" /> ";
                    in.readLine();
                    continue;
                }
            }
            if (str.contains("<table id=\"mainTable\">")) {
                found = true;

            }

            if (found) {
                while ((str = in.readLine()) != null) {

                    //   System.out.println("" + str + "\n");
                    if (str.contains("</tr>")) {
                        found = false;
                        readingdone = true;
                        content1 += replace;
                        break;

                    }
                }

            }

        }
        in.close();
        BufferedWriter out = new BufferedWriter(new FileWriter(f));
        // System.out.println("***"+content1);
        out.write(content1);
        out.close();

    } catch (IOException e) {
    }
}