很想把这两个类的用法记下来,因为它们是我在Reader和Writer类层次结构中找到仅有的可以指定字符编码集(Charset)的输入输出类。这里两个类分别举一个例子来说明它俩的用法,它们分别作为InputStream和OutputStream的装饰者。
public void test1() { InputStream in; Charset charset = Charset.forName("UTF-8"); try { in = new FileInputStream("test1.txt"); // charset指定的是字符流原来的字符编码集 Reader reader = new InputStreamReader(in, charset); int temp; while ((temp = reader.read()) != -1) { char c = (char) temp; System.out.print(c); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void test2() { Charset charset = Charset.forName("UTF-8"); try { OutputStream outputStream = new FileOutputStream("test1.txt"); // charset指定的是字符流输出的字符编码集 Writer writer = new OutputStreamWriter(outputStream, charset); writer.write("<span><span class="string">liyuncong wangfang 李</span></span>"); writer.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
Java InputStreamReader和OutputStreamWriter
原文地址:http://blog.csdn.net/l294265421/article/details/47425875