Example usage for java.io OutputStreamWriter getEncoding

List of usage examples for java.io OutputStreamWriter getEncoding

Introduction

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

Prototype

public String getEncoding() 

Source Link

Document

Returns the name of the character encoding being used by this stream.

Usage

From source file:Main.java

public static void main(String[] args) {

    try {/*w w w.j  a  va  2  s. c  o m*/
        OutputStream os = new FileOutputStream("test.txt");
        OutputStreamWriter writer = new OutputStreamWriter(os);

        // create a new FileInputStream to read what we write
        FileInputStream in = new FileInputStream("test.txt");

        // write something in the file
        writer.write(70);

        // flush the stream
        writer.flush();

        // get and print the encoding for this stream
        System.out.println(writer.getEncoding());

        // read what we write
        System.out.println((char) in.read());
        writer.close();
        os.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

/**
 * Get the default system encoding using a writer
 * @param inWriter writer object//from w  ww  .  ja va2s .  c o m
 * @return string defining encoding
 */
public static String getEncoding(OutputStreamWriter inWriter) {
    String encoding = inWriter.getEncoding();
    try {
        encoding = Charset.forName(encoding).name();
    } catch (Exception e) {
    } // ignore failure to find encoding
    return encoding;
}

From source file:org.structr.csv.test.StructrCsvTest.java

private static String getEncodingInUse() {
    OutputStreamWriter writer = new OutputStreamWriter(new ByteArrayOutputStream());
    return writer.getEncoding();
}

From source file:org.kalypso.ogc.sensor.tableview.TableViewUtils.java

/**
 * Saves the given template (binding). Closes the writer.
 *//*from  ww w  .java 2 s. c om*/
public static void saveTableTemplateXML(final Obstableview xml, final OutputStreamWriter writer)
        throws JAXBException {
    try {
        final Marshaller m = JaxbUtilities.createMarshaller(OTT_JC);
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_ENCODING, writer.getEncoding());
        m.marshal(xml, writer);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.kalypso.ogc.sensor.diagview.DiagViewUtils.java

/**
 * Saves the given template (binding). Closes the writer.
 *//*from w w  w .ja v  a2 s.  c  o  m*/
public static void saveDiagramTemplateXML(final Obsdiagview tpl, final OutputStreamWriter writer)
        throws JAXBException {
    try {

        final Marshaller m = createMarshaller();
        String encoding = writer.getEncoding();
        // HACK: rename utf8 encoding, esle xml editor will not validate
        if ("UTF8".equals(encoding)) //$NON-NLS-1$
            encoding = "UTF-8"; //$NON-NLS-1$

        m.setProperty(Marshaller.JAXB_ENCODING, encoding);

        m.marshal(tpl, writer);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.kalypso.ogc.gml.serialize.GmlSerializer.java

public static void serializeWorkspace(final OutputStreamWriter writer, final GMLWorkspace workspace)
        throws GmlSerializeException {
    serializeWorkspace(writer, workspace, writer.getEncoding());
}

From source file:com.databasepreservation.cli.CLI.java

private static String getDefaultCharSet() {
    OutputStreamWriter dummyWriter = new OutputStreamWriter(new ByteArrayOutputStream());
    String encoding = dummyWriter.getEncoding();
    return encoding;
}

From source file:org.kalypso.kalypsosimulationmodel.utils.SLDHelper.java

private static void exportSLD(final IFile sldFile, final StyledLayerDescriptor descriptor,
        final IProgressMonitor progressMonitor) throws IOException, SAXException, CoreException {
    // FIXME: ugly! The bug is elsewhere!
    if (!sldFile.isSynchronized(IResource.DEPTH_ZERO))
        sldFile.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());

    final ByteArrayInputStream stream = new ByteArrayInputStream(descriptor.exportAsXML().getBytes("UTF-8")); //$NON-NLS-1$
    final Document doc = XMLTools.parse(stream);
    final Source source = new DOMSource(doc);

    final SetContentHelper helper = new SetContentHelper() {
        @Override//from w  ww.ja va2 s.  c  o  m
        protected void write(final OutputStreamWriter writer) throws Throwable {
            try {
                final StreamResult result = new StreamResult(writer);
                final TransformerFactory factory = TransformerFactory.newInstance();

                // Comment from Dejan: this works only with Java 1.5, in 1.4 it throws IllegalArgumentException
                // also, indentation doesn't works with OutputStream, only with OutputStreamWriter :)
                try {
                    factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$
                } catch (final IllegalArgumentException e) {
                }

                final Transformer transformer = factory.newTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, writer.getEncoding());
                transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$

                // transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "2" );
                // //$NON-NLS-1$
                // //$NON-NLS-2$
                // transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
                // transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$

                transformer.transform(source, result);
            } finally {
                IOUtils.closeQuietly(writer);
            }
        }
    };

    if (progressMonitor.isCanceled())
        throw new CoreException(Status.CANCEL_STATUS);

    helper.setFileContents(sldFile, false, false, progressMonitor);
}

From source file:com.streamsets.pipeline.lib.generator.delimited.TestDelimitedDataGenerator.java

@Test
public void testFactory() throws Exception {
    Stage.Context context = ContextInfoCreator.createTargetContext("i", false, OnRecordError.TO_ERROR);

    DataGeneratorFactoryBuilder builder = new DataGeneratorFactoryBuilder(context,
            DataGeneratorFormat.DELIMITED);
    builder.setMode(CsvMode.CSV).setMode(CsvHeader.IGNORE_HEADER).setCharset(Charset.forName("US-ASCII"));
    DataFactory dataFactory = builder.build();

    Assert.assertTrue(dataFactory instanceof DelimitedDataGeneratorFactory);
    DelimitedDataGeneratorFactory factory = (DelimitedDataGeneratorFactory) dataFactory;

    DelimitedCharDataGenerator generator = (DelimitedCharDataGenerator) factory
            .getGenerator(new ByteArrayOutputStream());
    Assert.assertEquals(CSVFormat.DEFAULT, generator.getFormat());
    Assert.assertEquals(CsvHeader.IGNORE_HEADER, generator.getHeader());
    Assert.assertEquals("header", generator.getHeaderKey());
    Assert.assertEquals("value", generator.getValueKey());

    Writer writer = factory.createWriter(new ByteArrayOutputStream());
    Assert.assertTrue(writer instanceof OutputStreamWriter);
    OutputStreamWriter outputStreamWriter = (OutputStreamWriter) writer;
    Assert.assertEquals("ASCII", outputStreamWriter.getEncoding());

    builder = new DataGeneratorFactoryBuilder(context, DataGeneratorFormat.DELIMITED);
    builder.setMode(CsvMode.CSV).setMode(CsvHeader.IGNORE_HEADER)
            .setConfig(DelimitedDataGeneratorFactory.HEADER_KEY, "foo")
            .setConfig(DelimitedDataGeneratorFactory.VALUE_KEY, "bar");
    dataFactory = builder.build();//from   w w  w  . j  av  a 2  s  . c o m
    Assert.assertTrue(dataFactory instanceof DelimitedDataGeneratorFactory);
    factory = (DelimitedDataGeneratorFactory) dataFactory;

    generator = (DelimitedCharDataGenerator) factory.getGenerator(new ByteArrayOutputStream());
    Assert.assertEquals("foo", generator.getHeaderKey());
    Assert.assertEquals("bar", generator.getValueKey());

}

From source file:org.apache.jackrabbit.core.persistence.xml.XMLPersistenceManager.java

/**
 * {@inheritDoc}/*from w w w  .ja va 2 s  .  c o  m*/
 */
protected void store(NodeReferences refs) throws ItemStateException {
    if (!initialized) {
        throw new IllegalStateException("not initialized");
    }

    String refsFilePath = buildNodeReferencesFilePath(refs.getTargetId());
    FileSystemResource refsFile = new FileSystemResource(itemStateFS, refsFilePath);
    try {
        refsFile.makeParentDirs();
        OutputStream os = refsFile.getOutputStream();
        BufferedWriter writer = null;
        try {
            String encoding = DEFAULT_ENCODING;
            try {
                writer = new BufferedWriter(new OutputStreamWriter(os, encoding));
            } catch (UnsupportedEncodingException e) {
                // should never get here!
                OutputStreamWriter osw = new OutputStreamWriter(os);
                encoding = osw.getEncoding();
                writer = new BufferedWriter(osw);
            }
            writer.write("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n");
            writer.write("<" + NODEREFERENCES_ELEMENT + " " + TARGETID_ATTRIBUTE + "=\"" + refs.getTargetId()
                    + "\">\n");
            // write references (i.e. the id's of the REFERENCE properties)
            for (PropertyId propId : refs.getReferences()) {
                writer.write(
                        "\t<" + NODEREFERENCE_ELEMENT + " " + PROPERTYID_ATTRIBUTE + "=\"" + propId + "\"/>\n");
            }
            writer.write("</" + NODEREFERENCES_ELEMENT + ">\n");
        } finally {
            writer.close();
        }
    } catch (Exception e) {
        String msg = "failed to store " + refs;
        log.debug(msg);
        throw new ItemStateException(msg, e);
    }
}