如何在UTF8字节数组之间来回转换字符串

以下示例将展示使用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());
   //获取UTF-8数据读取器
   reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
   
   //将UTF-8转换为Unicode-
   int data = reader.read();
   while(data != -1){
      char theChar = (char) data;
      System.out.print(theChar);
      data = reader.read();
   } reader.close();
   System.out.println();
   //将Unicode转换为UTF-8字节
   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); }
}

输出结果

It will print the following result.
This is a sample text This is a sample text