📜  Java内部化-读/写器之间的Unicode转换

📅  最后修改于: 2020-11-15 03:42:25             🧑  作者: Mango


Reader和Writer类是面向字符的流类。这些可以用来读取和转换Unicode字符。

转换次数

下面的示例将展示使用Reader和Writer类将Unicode字符串转换为UTF8字节[],并将UTF8字节[]转换为Unicode字节[]。

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

打印