在整个io包中,实际上就分为字符流和字节流,但是,除了这两个流之外还存在一个 字符流-字节流转换类。
OutputStreamWriter是字符流通向字节流的桥梁:可使用指定的 将要写入流中的字符编码成字节。它使用的字符集可以由名称指定或显式给定,否则将接受平台默认的字符集。
InputStreamReader 是 字节流通向字符流的桥梁:它使用指定的 读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。
import java.io.* ; public class OutputStreamWriterDemo01{ public static void main(String args[]) throws Exception { // 所有异常抛出 File f = new File( "d:" + File.separator + "test.txt") ; Writer out = null ; // 字符输出流 out = new OutputStreamWriter( new FileOutputStream(f)) ; // 字节流变为字符流 out.write( "hello world!!") ; // 使用字符流输出 out.close() ; } };
import java.io.* ; public class InputStreamReaderDemo01{ public static void main(String args[]) throws Exception{ File f = new File( "d:" + File.separator + "test.txt") ; Reader reader = null ; reader = new InputStreamReader( new FileInputStream(f)) ; // 将字节流变为字符流 char c[] = new char[1024] ; int len = reader.read(c) ; // 读取 reader.close() ; // 关闭 System.out.println( new String(c,0,len)) ; } };