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:ilearnrw.utils.ServerHelperClass.java

public static String sendPost(String link, String urlParameters) throws Exception {
    String url = baseUrl + link;/*from   www  . j  a va  2s.c  o  m*/

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api"));

    con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    con.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF8");

    wr.write(urlParameters);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}

From source file:Main.java

/**
 * Saves a DOM to a human-readable XML file (4-space indentation, UTF-8).
 * <p>//from w ww  .ja v  a2 s. c  o m
 * Contains workaround for various JVM bugs.
 * 
 * @param document
 *        The DOM
 * @param file
 *        The target XML file
 * @throws TransformerFactoryConfigurationError
 *         In case of an XML transformation factory configuration error
 * @throws TransformerException
 *         In case of an XML transformation error
 * @throws IOException
 *         In case of an I/O error
 */
public static void saveHumanReadable(Document document, File file)
        throws TransformerFactoryConfigurationError, TransformerException, IOException {
    // Various indentation and UTF8 encoding bugs are worked around here
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setAttribute("indent-number", new Integer(4));
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF8");
    transformer.transform(new DOMSource(document), new StreamResult(writer));
    writer.close();
}

From source file:com.predic8.membrane.core.ws.relocator.RelocatorTest.java

@Override
protected void setUp() throws Exception {
    relocator = new Relocator(new OutputStreamWriter(NullOutputStream.NULL_OUTPUT_STREAM, Constants.UTF_8),
            "http", "localhost", 3000, null);
    super.setUp();
}

From source file:juicebox.tools.utils.juicer.apa.APAUtils.java

/**
 * @param filename/*from  w  w  w. ja v  a 2 s.  com*/
 * @param matrix
 */
public static void saveMeasures(String filename, RealMatrix matrix) {

    Writer writer = null;

    APARegionStatistics apaStats = new APARegionStatistics(matrix);

    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
        writer.write("P2M" + '\t' + apaStats.getPeak2mean() + '\n');
        writer.write("P2UL" + '\t' + apaStats.getPeak2UL() + '\n');
        writer.write("P2UR" + '\t' + apaStats.getPeak2UR() + '\n');
        writer.write("P2LL" + '\t' + apaStats.getPeak2LL() + '\n');
        writer.write("P2LR" + '\t' + apaStats.getPeak2LR() + '\n');
        writer.write("ZscoreLL" + '\t' + apaStats.getZscoreLL());
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:net.ontopia.xml.ContentWriter.java

public ContentWriter(String file) throws IOException {
    out = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
}

From source file:com.fuzz.android.limelight.util.JSONTool.java

/**
 * Entry point writer method that starts the call of other writer methods.
 *
 * @param outputStream//from   w w  w.  jav a 2  s .com
 * @param book
 * @throws IOException
 */
public static void writeJSON(OutputStream outputStream, Book book) throws IOException {
    JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
    writer.setIndent("  ");
    writeBook(writer, book);
    writer.close();
}

From source file:com.adr.raspberryleds.HTTPUtils.java

public static JSONObject execPOST(String address, JSONObject params) throws IOException {

    BufferedReader readerin = null;
    Writer writerout = null;//from   w  w  w.  j  a va 2s  .  c om

    try {
        URL url = new URL(address);
        String query = params.toString();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8");
        connection.addRequestProperty("Content-length", String.valueOf(query.length()));

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONObject result = new JSONObject(text.toString());

            if (result.has("exception")) {
                throw new IOException(
                        MessageFormat.format("Remote exception: {0}.", result.getString("exception")));
            } else {
                return result;
            }
        } else {
            throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}",
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
    } catch (JSONException ex) {
        throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage()));
    } finally {
        if (writerout != null) {
            writerout.close();
            writerout = null;
        }
        if (readerin != null) {
            readerin.close();
            readerin = null;
        }
    }
}

From source file:net.bioclipse.model.ImageWriter.java

/**
 * Save image to svg format//from ww w.j  a v a 2s  . c  om
 * @param path the path including filename where the image is to be stored
 * @param chart TODO
 */
public static void saveImageSVG(String path, JFreeChart chart) {
    //First check that we have a valid chart
    if (chart != null) {
        //Create DOM objects
        DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
        Document document = domImpl.createDocument(null, "svg", null);

        //Create an instance of the SVG generator
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

        //Setting the precision apparently avoids a NullPointerException in Batik 1.5
        svgGenerator.getGeneratorContext().setPrecision(6);

        //Render chart into SVG Graphics2D impl.
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, 400, 300), null);

        //Write to file
        boolean useCSS = true;
        try {
            Writer out = new OutputStreamWriter(new FileOutputStream(new File(path)), "UTF-8");
            svgGenerator.stream(out, useCSS);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SVGGraphics2DIOException e) {
            e.printStackTrace();
        }
    }

}

From source file:edu.cornell.mannlib.vitro.webapp.controller.datatools.dumprestore.JsonToNquads.java

public JsonToNquads(OutputStream out) throws IOException {
    this.writer = new OutputStreamWriter(out, "UTF-8");
    log.info("Dump beginning.");
}

From source file:com.netflix.config.DynamicFileConfigurationTest.java

static void modifyConfigFile() {
    new Thread() {
        public void run() {
            try {
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(configFile), "UTF-8"));
                writer.write("abc=-2"); // this property should fail validation but should not affect update of other properties
                writer.newLine();//from ww w.j  av a  2 s.  c  o m
                writer.write("dprops1=" + String.valueOf(Long.MIN_VALUE));
                writer.newLine();
                writer.write("dprops2=" + String.valueOf(Double.MAX_VALUE));
                writer.newLine();
                writer.close();
                System.err.println(configFile.getPath() + " modified");
            } catch (Exception e) {
                e.printStackTrace();
                fail("Unexpected exception");
            }
        }
    }.start();
}