Example usage for java.io OutputStreamWriter OutputStreamWriter

List of usage examples for java.io OutputStreamWriter OutputStreamWriter

Introduction

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

Prototype

public OutputStreamWriter(OutputStream out, CharsetEncoder enc) 

Source Link

Document

Creates an OutputStreamWriter that uses the given charset encoder.

Usage

From source file:Main.java

/**
 * Dump a <code>String</code> to a text file.
 *
 * @param file The output file//from   w w w  . j  a  v a  2 s. c  o m
 * @param string The string to be dumped
 * @param encoding The encoding for the output file or null for default platform encoding
 * @exception IOException IO Error
        
 */
public static void serializeString(File file, String string, String encoding) throws IOException {
    final Writer fw = (encoding == null) ? new FileWriter(file)
            : new OutputStreamWriter(new FileOutputStream(file), encoding);
    try {
        fw.write(string);
        fw.flush();
    } finally {
        fw.close();
    }
}

From source file:Main.java

public static String UpdateScore(String userName, int br) {

    String retStr = "";

    try {//  w  w w .jav  a 2  s.  c om
        URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        Log.e("http", "por1");

        JSONObject data = new JSONObject();

        data.put("username", userName);
        data.put("broj", br);

        Log.e("http", "por3");

        Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
        String query = builder.build().getEncodedQuery();

        Log.e("http", "por4");

        OutputStream os = conn.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(query);
        Log.e("http", "por5");
        bw.flush();
        bw.close();
        os.close();
        int responseCode = conn.getResponseCode();

        Log.e("http", String.valueOf(responseCode));
        if (responseCode == HttpURLConnection.HTTP_OK) {
            retStr = inputStreamToString(conn.getInputStream());
        } else
            retStr = String.valueOf("Error: " + responseCode);

        Log.e("http", retStr);

    } catch (Exception e) {
        Log.e("http", "greska");
    }
    return retStr;
}

From source file:Main.java

public static String UdatePlayerBT(String userName, String device) {

    String retStr = "";

    try {/*from  ww w  .j  av  a2  s. c  o m*/
        URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        Log.e("http", "por1");

        JSONObject data = new JSONObject();

        data.put("username", userName);
        data.put("bt_device", device);

        Log.e("http", "por3");

        Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
        String query = builder.build().getEncodedQuery();

        Log.e("http", "por4");

        OutputStream os = conn.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(query);
        Log.e("http", "por5");
        bw.flush();
        bw.close();
        os.close();
        int responseCode = conn.getResponseCode();

        Log.e("http", String.valueOf(responseCode));
        if (responseCode == HttpURLConnection.HTTP_OK) {
            retStr = inputStreamToString(conn.getInputStream());
        } else
            retStr = String.valueOf("Error: " + responseCode);

        Log.e("http", retStr);

    } catch (Exception e) {
        Log.e("http", "greska");
    }
    return retStr;
}

From source file:com.smart.common.officeFile.CSVUtils.java

/**
 *
 * @param exportData ?/*  ww  w.j a  v  a2  s  . c  o  m*/
 * @param rowMapper ??
 * @param outPutPath 
 * @param filename ??
 * @return
 */
public static File createCSVFile(List exportData, LinkedHashMap rowMapper, String outPutPath, String filename) {

    File csvFile = null;
    BufferedWriter csvFileOutputStream = null;
    try {
        csvFile = new File(outPutPath + filename + ".csv");
        // csvFile.getParentFile().mkdir();
        File parent = csvFile.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        csvFile.createNewFile();

        // GB2312?","
        csvFileOutputStream = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
        // 
        for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator.hasNext();) {
            java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
            csvFileOutputStream.write("\"" + propertyEntry.getValue().toString() + "\"");
            if (propertyIterator.hasNext()) {
                csvFileOutputStream.write(",");
            }
        }
        csvFileOutputStream.newLine();

        // 
        for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
            LinkedHashMap row = (LinkedHashMap) iterator.next();
            System.out.println(row);

            for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) {
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                // System.out.println(BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
                csvFileOutputStream.write("\"" + propertyEntry.getValue().toString() + "\"");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
            }

            //                for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) {
            //                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
            //                    System.out.println(BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
            //                    csvFileOutputStream.write("\""
            //                            + BeanUtils.getProperty(row, propertyEntry.getKey().toString()) + "\"");
            //                    if (propertyIterator.hasNext()) {
            //                        csvFileOutputStream.write(",");
            //                    }
            //                }
            if (iterator.hasNext()) {
                csvFileOutputStream.newLine();
            }
        }
        csvFileOutputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            csvFileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return csvFile;
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Locale locale;/*from  w w w . ja va2s. co  m*/
    DateFormat full;

    try {
        res.setContentType("text/plain; charset=UTF-8");
        //PrintWriter out = res.getWriter();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);

        locale = new Locale("en", "US");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In English appropriate for the US:");
        out.println("Hello World!");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("es", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("En Espa\u00f1ol:");
        out.println("\u00a1Hola Mundo!");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("ja", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In Japanese:");
        out.println("\u4eca\u65e5\u306f\u4e16\u754c");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("zh", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In Chinese:");
        out.println("\u4f60\u597d\u4e16\u754c");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("ko", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In Korean:");
        out.println("\uc548\ub155\ud558\uc138\uc694\uc138\uacc4");
        out.println(full.format(new Date()));
        out.println();

        locale = new Locale("ru", "");
        full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        out.println("In Russian (Cyrillic):");
        out.print("\u0417\u0434\u0440\u0430\u0432\u0441\u0442");
        out.println("\u0432\u0443\u0439, \u041c\u0438\u0440");
        out.println(full.format(new Date()));
        out.println();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//from ww w . j a  v a  2 s . c o  m
        // Get a reader to read the incoming data
        BufferedReader reader = req.getReader();

        // Get a writer to write the data in UTF-8
        res.setContentType("text/html; charset=UTF-8");
        //PrintWriter out = res.getWriter();
        out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);

        char[] buf = new char[4 * 1024]; // 4Kchar buffer
        int len;
        while ((len = reader.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();
    } catch (Exception e) {
        out.println("Problem filtering page to UTF-8");
        getServletContext().log(e, "Problem filtering page to UTF-8");
    }
    out.println("Done");
}

From source file:Main.java

@SuppressWarnings("UseSpecificCatch")
public static boolean saveXML(Document doc, File outfile, boolean indent) {
    try {/*from  w  ww. j av a 2 s .  c  o m*/
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"));
        if (indent) {
            XPathFactory xpathFactory = XPathFactory.newInstance();
            // XPath to find empty text nodes.
            XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
            NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);

            // Remove each empty text node from document.
            for (int i = 0; i < emptyTextNodes.getLength(); i++) {
                Node emptyTextNode = emptyTextNodes.item(i);
                emptyTextNode.getParentNode().removeChild(emptyTextNode);
            }
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        }
        transformer.transform(source, result);
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:UTF8.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {//from w w w . j av  a 2  s  .  c om
        BufferedReader reader = req.getReader();

        res.setContentType("text/html; charset=UTF-8");
        PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);

        // Read and write 4K chars at a time
        // (Far more efficient than reading and writing a line at a time)
        char[] buf = new char[4 * 1024]; // 4Kchar buffer
        int len;
        while ((len = reader.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();
    } catch (Exception e) {
        getServletContext().log(e, "Problem filtering page to UTF-8");
    }
}

From source file:com.raphfrk.craftproxyclient.json.JSONManager.java

public static byte[] JSONToBytes(JSONObject obj) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStreamWriter wos = new OutputStreamWriter(bos, StandardCharsets.UTF_8);
    BufferedWriter br = new BufferedWriter(wos);
    try {//from   w  ww  .  j  av a 2s  .c o  m
        obj.writeJSONString(br);
        br.close();
    } catch (IOException e) {
        return null;
    }
    return bos.toByteArray();
}

From source file:Main.java

/**
 * Print XML in "pretty" format.//  w  ww .j a va 2 s .c o  m
 * 
 * @param in an XML input stream
 * @param out where the result will go
 * @param indent the number of characters to indent
 */
public static void prettyPrintXml(InputStream in, OutputStream out, int indent) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // set indent spaces on factory
    //        tfactory.setAttribute("indent-number", new Integer(indent));

    try {
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(in);
        Transformer serializer = tfactory.newTransformer();

        // turn on indenting on transformer (serializer)
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                //                  String.valueOf(indent));
                "2");

        serializer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "utf-8")));
    } catch (Exception e) {

        // this is fatal, just dump stack and throw runtime exception
        e.printStackTrace();

        throw new RuntimeException(e);
    }
}