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:com.zhch.example.commons.http.v4_5.ProxyTunnelDemo.java

/**
 * ?? demo//from   w ww  .j a va 2 s .c  o m
 * 
 * @throws Exception
 */
public final static void officalDemo() throws Exception {
    ProxyClient proxyClient = new ProxyClient();
    HttpHost target = new HttpHost("www.yahoo.com", 80);
    HttpHost proxy = new HttpHost("localhost", 8888);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd");
    Socket socket = proxyClient.tunnel(proxy, target, credentials);
    try {
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Agent: whatever\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } finally {
        socket.close();
    }
}

From source file:com.textocat.textokit.commons.io.IoUtils.java

public static BufferedWriter openBufferedWriter(File file, String encoding, boolean append) throws IOException {
    FileOutputStream fos = openOutputStream(file, append);
    OutputStreamWriter osr;/*w ww.j  a  va  2  s.  c om*/
    try {
        osr = new OutputStreamWriter(fos, encoding);
    } catch (UnsupportedEncodingException e) {
        closeQuietly(fos);
        throw e;
    }
    return new BufferedWriter(osr);
}

From source file:eu.planets_project.tb.utils.ExperimentUtils.java

/**
 * //www  . j  a va  2s  . com
 * @param os
 * @param expId
 * @throws IOException 
 */
public static void outputResults(OutputStream os, String expId, DATA_FORMAT format) throws IOException {
    log.info("Writing out experiment " + expId + " as " + format);

    Writer out = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    CSVWriter writer = new CSVWriter(out);

    long id = Long.parseLong(expId);

    ExperimentPersistencyRemote edao = ExperimentPersistencyImpl.getInstance();
    Experiment exp = edao.findExperiment(id);

    // The string array 
    String sa[] = new String[8];
    sa[0] = "Name";
    sa[1] = "Run #";
    sa[2] = "Date";
    sa[3] = "Digital Object #";
    sa[4] = "Digital Object Source";
    sa[5] = "Stage";
    sa[6] = "Property Identifier";
    sa[7] = "Property Value";
    // write the headers out:
    writer.writeNext(sa);

    // Loop through:
    int bi = 1;
    for (BatchExecutionRecordImpl batch : exp.getExperimentExecutable().getBatchExecutionRecords()) {
        // log.info("Found batch... "+batch);
        int doi = 1;
        for (ExecutionRecordImpl exr : batch.getRuns()) {
            // log.info("Found Record... "+exr+" stages: "+exr.getStages());
            if (exr != null && exr.getStages() != null) {
                for (ExecutionStageRecordImpl exsr : exr.getStages()) {
                    // log.info("Found Stage... "+exsr);
                    for (MeasurementImpl m : exsr.getMeasurements()) {
                        // log.info("Looking at result for property "+m.getIdentifier());
                        sa[0] = exp.getExperimentSetup().getBasicProperties().getExperimentName();
                        sa[1] = "" + bi;
                        sa[2] = batch.getStartDate().getTime().toString();
                        sa[3] = "" + doi;
                        sa[4] = exr.getDigitalObjectSource();
                        sa[5] = exsr.getStage();
                        sa[6] = m.getIdentifier();
                        sa[7] = m.getValue();
                        // Write out CSV:
                        writer.writeNext(sa);
                    }
                }
            }
            // Increment, for the next DO.
            doi++;
            out.flush();
        }
        // Increment to the next batch:
        bi++;
    }

}

From source file:actuatorapp.ActuatorApp.java

public ActuatorApp() throws IOException, JSONException {
    //Takes a sting with a relay name "RELAYLO1-10FAD.relay1"
    //Actuator a = new Actuator("RELAYLO1-12854.relay1");    
    //Starts the virtualhub that is needed to connect to the actuators
    Process process = new ProcessBuilder("src\\actuatorapp\\VirtualHub.exe").start();
    //{"yocto_addr":"10FAD","payload":{"value":true},"type":"control"}

    api = new Socket("10.42.72.25", 8082);
    OutputStreamWriter osw = new OutputStreamWriter(api.getOutputStream(), StandardCharsets.UTF_8);
    InputStreamReader isr = new InputStreamReader(api.getInputStream(), StandardCharsets.UTF_8);

    //Sends JSON authentication to CommandAPI
    JSONObject secret = new JSONObject();
    secret.put("type", "authenticate");
    secret.put("secret", "testpass");
    osw.write(secret.toString() + "\r\n");
    osw.flush();// w  w  w  .  j a  v a  2  s . c o m
    System.out.println("sent");

    //Waits and recieves JSON authentication response
    BufferedReader br = new BufferedReader(isr);
    JSONObject response = new JSONObject(br.readLine());
    System.out.println(response.toString());
    if (!response.getBoolean("success")) {
        System.err.println("Invalid API secret");
        System.exit(1);
    }

    try {
        while (true) {
            //JSON object will contain message from the server
            JSONObject type = getCommand(br);
            //Forward the command to be processed (will find out which actuators to turn on/off)
            commandFromApi(type);
        }
    } catch (Exception e) {
        System.out.println("Error listening to api");
    }

}

From source file:biz.ganttproject.impex.csv.CsvWriterImpl.java

CsvWriterImpl(OutputStream stream, CSVFormat format) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(stream, Charsets.UTF_8);
    myCsvPrinter = new CSVPrinter(writer, format);
}

From source file:com.linkedin.databus.core.util.StringUtils.java

public static Writer createFileWriter(File file) throws FileNotFoundException {
    return new OutputStreamWriter(new FileOutputStream(file), StringUtils.DEFAULT_CHARSET);
}

From source file:Main.java

public static void printDocument(Document doc, OutputStream out, boolean prettyPrint)
        throws IOException, TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (prettyPrint) {
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    }/*from   w ww  .  j a  va 2 s  .c o m*/

    transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}

From source file:com.beyondb.geocoding.BaiduAPI.java

public static Map<String, String> testPost(String x, String y) throws IOException {
    URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "="
            + "&callback=renderReverse&location=" + x + "," + y + "&output=json");
    URLConnection connection = url.openConnection();
    /**/*w ww. j a v a 2  s. c o  m*/
     * ??URLConnection?Web
     * URLConnection???Web???
     */
    connection.setDoOutput(true);
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
    //        remember to clean up
    out.flush();
    out.close();
    //        ?????
    String res;
    InputStream l_urlStream;
    l_urlStream = connection.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
    StringBuilder sb = new StringBuilder("");
    while ((res = in.readLine()) != null) {
        sb.append(res.trim());
    }
    String str = sb.toString();
    System.out.println(str);
    Map<String, String> map = null;
    if (StringUtils.isNotEmpty(str)) {
        int addStart = str.indexOf("formatted_address\":");
        int addEnd = str.indexOf("\",\"business");
        if (addStart > 0 && addEnd > 0) {
            String address = str.substring(addStart + 20, addEnd);
            map = new HashMap<String, String>();
            map.put("address", address);
            return map;
        }
    }

    return null;

}

From source file:Main.java

public static void writeDomToFile(Document dom, File outFile, Properties outputProperties) {
    //        try {
    //            StringWriter ret = new StringWriter();
    //            TransformerFactory transFact = TransformerFactory.newInstance();
    ////                transFact.setAttribute("indent-number", 2);
    //            Transformer transformer = transFact.newTransformer();
    //            if (outputProperties != null) transformer.setOutputProperties(outputProperties);
    //            DOMSource source = new DOMSource(dom);
    //            StreamResult result = new StreamResult(ret);

    try {/* w  w  w .  j a  v  a 2 s.c  om*/
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer transformer = transFact.newTransformer();
        if (outputProperties != null)
            transformer.setOutputProperties(outputProperties);
        DOMSource source = new DOMSource(dom);
        StreamResult result;

        result = new StreamResult(
                new OutputStreamWriter(new FileOutputStream(outFile), System.getProperty("file.encoding")));
        transformer.transform(source, result);
    } catch (Exception e) {
        throw new RuntimeException(
                "Could not write dom tree '" + dom.getBaseURI() + "' to file '" + outFile.getName() + "'!", e);
    }
}

From source file:net.grinder.util.LogCompressUtils.java

/**
 * Compress multiple Files with the given encoding.
 *
 * @param logFiles     files to be compressed
 * @param fromEncoding log file encoding
 * @param toEncoding   compressed log file encoding
 * @return compressed file byte array/*w w  w  .  j av a2  s. c  o  m*/
 */
public static byte[] compress(File[] logFiles, Charset fromEncoding, Charset toEncoding) {
    FileInputStream fis = null;
    InputStreamReader isr = null;
    ByteArrayOutputStream out = null;
    ZipOutputStream zos = null;
    OutputStreamWriter osw = null;
    if (toEncoding == null) {
        toEncoding = Charset.defaultCharset();
    }
    if (fromEncoding == null) {
        fromEncoding = Charset.defaultCharset();
    }
    try {
        out = new ByteArrayOutputStream();
        zos = new ZipOutputStream(out);
        osw = new OutputStreamWriter(zos, toEncoding);
        for (File each : logFiles) {
            try {
                fis = new FileInputStream(each);
                isr = new InputStreamReader(fis, fromEncoding);
                ZipEntry zipEntry = new ZipEntry(each.getName());
                zipEntry.setTime(each.lastModified());
                zos.putNextEntry(zipEntry);
                char[] buffer = new char[COMPRESS_BUFFER_SIZE];
                int count;
                while ((count = isr.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) {
                    osw.write(buffer, 0, count);
                }
                osw.flush();
                zos.flush();
                zos.closeEntry();
            } catch (IOException e) {
                LOGGER.error("Error occurs while compressing {} : {}", each.getAbsolutePath(), e.getMessage());
                LOGGER.debug("Details ", e);
            } finally {
                IOUtils.closeQuietly(isr);
                IOUtils.closeQuietly(fis);
            }
        }
        zos.finish();
        zos.flush();
        return out.toByteArray();
    } catch (IOException e) {
        LOGGER.error("Error occurs while compressing log : {} ", e.getMessage());
        LOGGER.debug("Details : ", e);
        return null;
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(osw);
    }
}