Charset

Charset 给出了Unicode和本地字符集之间的映射。由于windows系统使用本地字符集显示字符文件,java中的字符串用unicode表示。所以如果直接用DataOutputStream类写入字符串信息到文件,windows打开时将不能正确显示。这时需要一个OutputStreamWriter类来将Unicode字符串转换成本地字符串后再进行写入。OutputStreamWriter类的writer方法可以选择转换所使用的字符集。PrintWriter类内部自动包含了一个OutputStreamWriter对象。

 

 public static void main(String[] args) throws IOException {
  
  OutputStream fos =  new BufferedOutputStream(new FileOutputStream("src/test.txt"));
  OutputStreamWriter writer = new OutputStreamWriter(fos);
  writer.write("hello,my friends");
  writer.close() ;
 }

 

 

 public static void main(String[] args) throws IOException {
  
  InputStream fos =  new BufferedInputStream(new FileInputStream("src/test.txt"));
  InputStreamReader reader = new InputStreamReader(fos);
  char c = (char)reader.read() ;
  System.out.println(c);
  reader.close() ;
 }

}

 

posted on 2010-07-14 09:57  sunliho  阅读(423)  评论(0编辑  收藏  举报