Java-i18n-unicode-stream

提供:Dev Guides
移動先:案内検索

Javaの内部化-リーダー/ライターとのUnicode変換

ReaderおよびWriterクラスは、文字指向のストリームクラスです。 これらは、Unicode文字の読み取りと変換に使用できます。

変換

次の例では、ReaderクラスとWriterクラスを使用して、Unicode文字列をUTF8 byte []に​​、UTF8 byte []をUnicode byte []に​​変換する例を示します。

IOTester.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.text.ParseException;

public class I18NTester {
   public static void main(String[] args) throws ParseException, IOException {

      String input = "This is a sample text" ;

      InputStream inputStream = new ByteArrayInputStream(input.getBytes());

     //get the UTF-8 data
      Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));

     //convert UTF-8 to Unicode
      int data = reader.read();
      while(data != -1){
         char theChar = (char) data;
         System.out.print(theChar);
         data = reader.read();
      }
      reader.close();

      System.out.println();

     //Convert Unicode to UTF-8 Bytes
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      Writer writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));

      writer.write(input);
      writer.close();

      String out = new String(outputStream.toByteArray());

      System.out.println(out);
   }
}

出力

次の結果が出力されます。

This is a sample text
This is a sample text

link:/cgi-bin/printpage.cgi [__印刷]