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:foam.dao.HTTPSink.java

@Override
public void put(Object obj, Detachable sub) {
    HttpURLConnection conn = null;
    OutputStream os = null;/*w  w w .  ja  v a2 s.  c o m*/
    BufferedWriter writer = null;

    try {
        Outputter outputter = null;
        conn = (HttpURLConnection) new URL(url_).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        if (format_ == Format.JSON) {
            outputter = new foam.lib.json.Outputter(OutputterMode.NETWORK);
            conn.addRequestProperty("Accept", "application/json");
            conn.addRequestProperty("Content-Type", "application/json");
        } else if (format_ == Format.XML) {
            // TODO: make XML Outputter
            conn.addRequestProperty("Accept", "application/xml");
            conn.addRequestProperty("Content-Type", "application/xml");
        }
        conn.connect();

        os = conn.getOutputStream();
        writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
        writer.write(outputter.stringify((FObject) obj));
        writer.flush();
        writer.close();
        os.close();

        // check response code
        int code = conn.getResponseCode();
        if (code != HttpServletResponse.SC_OK) {
            throw new RuntimeException("Http server did not return 200.");
        }
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(os);
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:joachimeichborn.geotag.io.writer.kml.KmlWriter.java

/**
 * Create the output KML file containing:
 * <ul>//from  w w  w.j av a  2  s  .c  o  m
 * <li>placemarks for all positions
 * <li>a path connecting all positions in chronological order
 * <li>circles showing the accuracy information for all positions
 * </ul>
 * 
 * @throws IOException
 */
public void write(final Track aTrack, final Path aOutputFile) throws IOException {
    final String documentTitle = FilenameUtils.removeExtension(aOutputFile.getFileName().toString());

    final GeoTagKml kml = createKml(documentTitle, aTrack);

    try (final Writer kmlWriter = new OutputStreamWriter(
            new BufferedOutputStream(new FileOutputStream(aOutputFile.toFile())), StandardCharsets.UTF_8)) {
        kml.marshal(kmlWriter);
    }

    logger.fine("Wrote track to " + aOutputFile);
}

From source file:heigit.ors.util.FileUtility.java

public static void writeFile(String fileName, String encoding, String content) throws IOException {
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), encoding));
    out.append(content);//  w  w w .  j  a v a2 s.c  om
    out.flush();
    out.close();
}

From source file:com.streamsets.pipeline.lib.generator.DataGeneratorFactory.java

public Writer createWriter(OutputStream os) {
    return new OutputStreamWriter(os, getSettings().getCharset());
}

From source file:org.apache.solr.client.solrj.SolrSchemalessExampleTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    File tempSolrHome = createTempDir().toFile();
    // Schemaless renames schema.xml -> schema.xml.bak, and creates + modifies conf/managed-schema,
    // which violates the test security manager's rules, which disallow writes outside the build dir,
    // so we copy the example/example-schemaless/solr/ directory to a new temp dir where writes are allowed.
    FileUtils.copyFileToDirectory(new File(ExternalPaths.SERVER_HOME, "solr.xml"), tempSolrHome);
    File collection1Dir = new File(tempSolrHome, "collection1");
    FileUtils.forceMkdir(collection1Dir);
    FileUtils.copyDirectoryToDirectory(new File(ExternalPaths.SCHEMALESS_CONFIGSET), collection1Dir);
    Properties props = new Properties();
    props.setProperty("name", "collection1");
    OutputStreamWriter writer = null;
    try {//www  . j  a  va  2s  .  c  o m
        writer = new OutputStreamWriter(FileUtils.openOutputStream(new File(collection1Dir, "core.properties")),
                "UTF-8");
        props.store(writer, null);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception ignore) {
            }
        }
    }
    createJetty(tempSolrHome.getAbsolutePath());
}

From source file:modnlp.capte.AlignerUtils.java

public static void convertLineEndings(String inputfile, String outputfile) {
    /* This is a quick hackaround to convert the line endings from
     *  Windows files into Unix line endings so that the sentence splitter will work
     *  Seems to work, but hasn't been extensively tested.
     *//*  w  w  w. j  a  v a  2  s.c  o  m*/
    try {
        File input = new File(inputfile);
        File output = new File(outputfile);
        BufferedReader bb = new BufferedReader(new InputStreamReader(new FileInputStream(inputfile), "UTF8"));
        PrintWriter bv = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputfile), "UTF8"));
        String l = "";
        while (bb.ready()) {
            l = bb.readLine();
            bv.write(l + "\n");
        }

        bb.close();
        bv.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.aircable.aircam.SL4A.java

public void connect() throws UnknownHostException, IOException, JSONException {
    proxy = AndroidProxy.sProxy;/*from   www.j av  a2s.  c  o m*/
    host = proxy.getAddress().getHostName();
    port = proxy.getAddress().getPort();
    secret = proxy.getSecret();

    connection = new Socket(host, port);
    input = new BufferedReader(new InputStreamReader(connection.getInputStream(), "8859_1"), 1 << 13);
    output = new PrintWriter(
            new OutputStreamWriter(new BufferedOutputStream(connection.getOutputStream(), 1 << 13), "8859_1"),
            true);
    id = 0;
    if (this.secret != null)
        try {
            this.callMethod("_authenticate", new JSONArray('[' + this.secret + ']'));
        } catch (RuntimeException e) {
            if (!e.getMessage().contains("Unknown RPC"))
                throw e;
        }
}

From source file:edu.unc.lib.dl.fedora.ClientUtils.java

/**
 * Serializes the FOXML 1.1 JDOM document to a UTF-8 byte array. This method is responsible for assuring that the
 * FOXML output contains "standalone" datastreams with locally declared namespaces as required by Fedora ingest.
 *
 * @param doc//from   www.ja  v  a2  s  .  c  om
 *           a FOXML 1.1 JDOM document
 * @return a byte array serialization of the Document
 */
public static byte[] serializeXML(Document doc) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer pw;
    try {
        pw = new OutputStreamWriter(baos, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new ServiceException("UTF-8 character encoding support is required", e);
    }
    try {
        // Filtering SAX Events before serializing.
        // This ensures that any XML datastreams have locally
        // declared namespaces, which is a Fedora ingest
        // requirement.

        OutputFormat format = new OutputFormat("XML", "UTF-8", true);
        format.setIndent(2);
        format.setIndenting(true);
        format.setPreserveSpace(false);
        format.setLineWidth(200);
        XMLSerializer serializer = new XMLSerializer(pw, format);
        ContentHandler chs = serializer.asContentHandler();
        StandaloneDatastreamOutputFilter filter = new StandaloneDatastreamOutputFilter();
        filter.setContentHandler(chs);
        SAXOutputter sax = new SAXOutputter();
        sax.setContentHandler(filter);
        sax.output(doc);
        pw.flush();
    } catch (JDOMException e) {
        throw new ServiceException("Could not generate SAX events from JDOM.", e);
    } catch (IOException e) {
        throw new ServiceException("Could not obtain a content handler for the appropriate format and writer.",
                e);
    }
    byte[] result = baos.toByteArray();
    if (log.isDebugEnabled()) {
        try (StringWriter sw = new StringWriter();
                ByteArrayInputStream is = new ByteArrayInputStream(result);) {
            for (int f = is.read(); f != -1; f = is.read()) {
                sw.write(f);
            }
            log.debug(sw.toString());
        } catch (IOException e) {
            throw new ServiceException(e);
        }
    }
    return result;
}

From source file:fr.calamus.common.tools.AbstractTxtFileAccess.java

/**
 * Prepares the file for writing; if the file exists, deletes it before.
 * @return/*from  w w  w . jav a2s . c o  m*/
 * @throws IOException
 */
protected BufferedWriter prepareBufferedWriter() throws IOException {
    File f = getFile();
    if (!f.getParentFile().exists())
        f.getParentFile().mkdirs();
    if (f.exists()) {
        f.delete();
        //log.debug("prepareBufferedWriter : " + f.getAbsolutePath() + " deleted");
    }
    f.createNewFile();
    //log.debug("prepareBufferedWriter : " + f.getAbsolutePath() + " created");
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(f), Charset.forName(charset)));
    return bw;
}

From source file:org.eluder.logback.ext.jackson.JsonWriter.java

public JsonWriter(OutputStream os, Charset charset, ObjectMapper mapper) throws IOException {
    generator = mapper.getFactory().createGenerator(new OutputStreamWriter(os, charset))
            .configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false)
            .setPrettyPrinter(new MinimalPrettyPrinter(""));
}