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:net.ontopia.xml.ContentWriter.java

public ContentWriter(String file, String encoding) throws IOException {
    out = new OutputStreamWriter(new FileOutputStream(file), encoding);
}

From source file:Main.java

public static void saveDocument(Document doc, File transform, File file) throws IOException {
    try {/* w  ww. j a  v  a  2s  .  co m*/
        TransformerFactory tFactory = TransformerFactory.newInstance();
        tFactory.setAttribute("indent-number", new Integer(2));
        Transformer transformer = tFactory.newTransformer(new StreamSource(transform));
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        FileOutputStream fos = new FileOutputStream(file.getPath());

        DOMSource source = new DOMSource(doc);
        CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder();
        StreamResult result = new StreamResult(new OutputStreamWriter(fos, utf8Encoder));

        transformer.transform(source, result);
        fos.close();
    } catch (TransformerException e) {
        throw new IOException(e);
    }
}

From source file:Main.java

public static InputStream getUTF8Stream(String s) {
    try {/*  w w  w.  j  av  a2s  .com*/
        ByteArrayOutputStream bas = new ByteArrayOutputStream();
        Writer w = new OutputStreamWriter(bas, "utf-8");
        w.write(s);
        w.close();
        byte[] ba = bas.toByteArray();
        ByteArrayInputStream bis = new ByteArrayInputStream(ba);
        return bis;
    } catch (IOException e) {
        throw new RuntimeException("should not happen");
    }
}

From source file:de.ailis.oneinstance.OneInstanceClient.java

/**
 * @see java.lang.Runnable#run()//from  w  w w  .  jav  a2 s  .  c  om
 */
@Override
public void run() {
    try {
        try {
            // Send the application ID.
            PrintWriter out = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream(), "UTF-8"));
            out.println(this.appId);
            out.flush();

            // Read the data from the client
            InputStream in = this.socket.getInputStream();
            ObjectInputStream objIn = new ObjectInputStream(in);
            File workingDir = (File) objIn.readObject();
            String[] args = (String[]) objIn.readObject();

            // Call event handler
            boolean result = OneInstance.getInstance().fireNewInstance(workingDir, args);

            // Send the result
            out.println(result ? "start" : "exit");
            out.flush();

            // Wait for client disconnect.
            in.read();
        } finally {
            this.socket.close();
        }
    } catch (IOException e) {
        LOG.error(e.toString(), e);
    } catch (ClassNotFoundException e) {
        LOG.error(e.toString(), e);
    }
}

From source file:cat.tv3.eng.rec.recomana.lupa.visualization.RecommendationToJson.java

private static void saveResults(JSONArray recomendations, String id) {
    Writer out;/*w  ww .  j a  va 2 s.com*/
    try {
        out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream("data_toVisualize/data_recommendation/recommendation_" + id + ".json"),
                "UTF-8"));
        try {
            out.write(recomendations.toJSONString());
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:jgnash.convert.exportantur.csv.CsvExport.java

public static void exportAccount(final Account account, final LocalDate startDate, final LocalDate endDate,
        final File file) {
    Objects.requireNonNull(account);
    Objects.requireNonNull(startDate);
    Objects.requireNonNull(endDate);
    Objects.requireNonNull(file);

    // force a correct file extension
    final String fileName = FileUtils.stripFileExtension(file.getAbsolutePath()) + ".csv";

    final CSVFormat csvFormat = CSVFormat.EXCEL.withQuoteMode(QuoteMode.ALL);

    try (final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
            Files.newOutputStream(Paths.get(fileName)), StandardCharsets.UTF_8);
            final CSVPrinter writer = new CSVPrinter(new BufferedWriter(outputStreamWriter), csvFormat)) {

        outputStreamWriter.write('\ufeff'); // write UTF-8 byte order mark to the file for easier imports

        writer.printRecord("Account", "Number", "Debit", "Credit", "Balance", "Date", "Timestamp", "Memo",
                "Payee", "Reconciled");

        // write the transactions
        final List<Transaction> transactions = account.getTransactions(startDate, endDate);

        final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2).toFormatter();

        final DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder().appendValue(YEAR, 4)
                .appendLiteral('-').appendValue(MONTH_OF_YEAR, 2).appendLiteral('-')
                .appendValue(DAY_OF_MONTH, 2).appendLiteral(' ').appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
                .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2)
                .toFormatter();//www . j av  a2 s. c o m

        for (final Transaction transaction : transactions) {
            final String date = dateTimeFormatter.format(transaction.getLocalDate());

            final String timeStamp = timestampFormatter.format(transaction.getTimestamp());

            final String credit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) < 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String debit = transaction.getAmount(account).compareTo(BigDecimal.ZERO) > 0 ? ""
                    : transaction.getAmount(account).abs().toPlainString();

            final String balance = account.getBalanceAt(transaction).toPlainString();

            final String reconciled = transaction.getReconciled(account) == ReconciledState.NOT_RECONCILED
                    ? Boolean.FALSE.toString()
                    : Boolean.TRUE.toString();

            writer.printRecord(account.getName(), transaction.getNumber(), debit, credit, balance, date,
                    timeStamp, transaction.getMemo(), transaction.getPayee(), reconciled);
        }
    } catch (final IOException e) {
        Logger.getLogger(CsvExport.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:com.jyzn.wifi.validate.platforminterface.SmsInterfaceImpl.java

@Override
public Map HttpSendSms(String postUrl, String postData) {
    String result = "";
    Map resultMap = Maps.newHashMap();
    try {//from  w  w  w  . j  ava  2 s . com
        //??POST
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Length", "" + postData.length());

        try {
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();//?
        } catch (IOException e) {
        }

        //???
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            resultMap.put("status", "fail");
            //return "fail";
        }

        //??
        String line;
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
        }
        resultMap.put("status", "sucess");
        resultMap.put("result", result);
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return resultMap;
}

From source file:Main.java

protected void saveToFile() {
    JFileChooser fileChooser = new JFileChooser();
    int retval = fileChooser.showSaveDialog(save);
    if (retval == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        if (file == null) {
            return;
        }/* www. jav a2  s.c om*/
        if (!file.getName().toLowerCase().endsWith(".txt")) {
            file = new File(file.getParentFile(), file.getName() + ".txt");
        }
        try {
            textArea.write(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            Desktop.getDesktop().open(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:de.weltraumschaf.groundzero.transform.SuppressionsWriter.java

/**
 * Writes the given suppressions to {@link CheckstyleSuppressions#getFileName() file}.
 *
 * @param suppression must not be {@code null}
 * @throws XmlOutputFileWriteException if the file can't be written
 *//*w  w w  . j  ava 2s.  c  o m*/
public void write(final CheckstyleSuppressions suppression) throws XmlOutputFileWriteException {
    Validate.notNull(suppression);

    try (FileOutputStream fos = new FileOutputStream(new File(suppression.getFileName()), false)) {
        try (BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fos, suppression.getEncoding()))) {
            br.write(suppression.getXmlContent());
            br.flush();
        }
        fos.flush();
    } catch (final IOException ex) {
        throw new XmlOutputFileWriteException(String.format(
                "ERROR: Excpetion thrown while writing suppresions file '%s'!", suppression.getFileName()), ex);
    }
}

From source file:ExecutorHttpd.java

public void run() {
    try {/* w  ww .j  a v  a  2 s.c  o  m*/
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), "8859_1"));
        OutputStream out = client.getOutputStream();
        PrintWriter pout = new PrintWriter(new OutputStreamWriter(out, "8859_1"), true);
        String request = in.readLine();
        System.out.println("Request: " + request);

        byte[] data = "hello".getBytes();
        out.write(data, 0, data.length);
        out.flush();
        client.close();
    } catch (IOException e) {
        System.out.println("I/O error " + e);
    }
}