整个Java的I/O包中实际上分为字节流和字符流
还存在一组”字节流--字符流“的转换类
1、OutputStreamWriter:是Writer的子类,将输出的字符流变为字节流
即将一个字符流的输出对象变为字节流的输出对象
2、InputStreamReader:是Reader的子类,将输入的字节流转换为字符流
即将一个字节流的输入对象变为字符流的输入对象
关闭规则:
由里到外
字符流转换为字节流OutputStreamWriter
public static void main(String[] args) throws IOException { //1、 File file = new File("d:\test.txt"); OutputStream out = new FileOutputStream(file); //2、 Writer writer = null; writer = new OutputStreamWriter(out); //3、 writer.write("天长地久"); //4、 writer.close(); out.close(); }
字节流转换为字符流InputStreamReader
public static void main(String[] args) throws IOException { //1、 File file = new File("d:\test.txt"); InputStream in = new FileInputStream(file); //2、 InputStreamReader reader = null; reader = new InputStreamReader(in); //3、 int res = 0; int len = 0; char [] b = new char[(int) file.length()]; while((res = reader.read()) !=-1){ b[len] = (char) res; len++; } //4、 reader.close(); in.close(); System.out.println(new String(b)); } }