Converting Character Streams and Buffers by using java.io.InputStreamReader to decode a byte stream to Unicode characters - Java Internationalization

Java examples for Internationalization:Unicode

Description

Converting Character Streams and Buffers by using java.io.InputStreamReader to decode a byte stream to Unicode characters

Demo Code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class Main {
  public static String readStream() throws IOException {
    InputStream is = new FileInputStream("s.txt");

    StringBuilder sb = new StringBuilder();
    if (is != null) {
      try (InputStreamReader reader = new InputStreamReader(is,
          Charset.forName("SJIS"))) {
        int ch = reader.read();
        while (ch != -1) {
          sb.append((char) ch);
          ch = reader.read();//from w ww .  j a  v  a2s .c  o m
        }
      }
    }
    return sb.toString();
  }

  public static void writeStream(String text) throws IOException {
    FileOutputStream fos = new FileOutputStream("utf8.txt");
    try (OutputStreamWriter writer = new OutputStreamWriter(fos,
        Charset.forName("UTF-8"))) {
      writer.write(text);
    }
  }
  public static void main(String[] args) throws Exception {
    String input = readStream();
    System.out.printf("Input stream: %s\n", input);
    writeStream(input);
  }

}

Related Tutorials