开发手册 欢迎您!
软件开发者资料库

Java内部化 - Unicode Conversion from/to Reader/Writer

Java内部化Unicode Conversion from/to Reader/Writer - 从简单和简单的步骤学习Java内部化从基本到高级概念,包括概述,环境设置,区域设置,区域设置详细信息,显示语言,ResourceBundle,NumberFormat,格式货币,格式百分比,设置最小/最大精度,设置舍入模式,解析数字,DecimalFormat,格式编号,区域设置特定DecimalFormat,DecimalFormatSymbols,分组数字,DateFormat,格式化日期,格式化时间,格式化日期和时间,SimpleDateFormat,解析日期,特定于区域设置的SimpleDateFormat, DateFormatSymbols,UTC,转换时区,可用时区

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

转换

以下示例将展示Unicode字符串到UTF8 byte []和UTF8的转换使用Reader和Writer类的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 textThis is a sample text