IO流总结
继承关系图
字符流和字节流的区别
- 字符流操作的时候会使用到缓冲区,而字节流操作的时候是不会使用到缓冲区的。
- 字符流多处理字符流,特别是中文字符以及一些文件的读写操作;字节流多处理一些二级制文件像图片、MP3、视频等。
字符流转向字节流的桥梁:InputStream和OutputStream
一个简单的例子
public class Bytes2Chars { /* * 测试输出字节流转向字符流 */ @Test public void InputStreamTest() throws IOException { File file = new File("e://u.txt"); if (!file.exists()) { file.createNewFile(); } InputStream is = new FileInputStream(file);// 字节流:不带缓冲----->字节流向字符流转化的中介 InputStreamReader isr = new InputStreamReader(is);// 字符流:带缓冲。但是输入流不带,输出流带。 char[] c = new char[1024]; StringBuilder sb = new StringBuilder(); while (isr.read(c) != -1) { sb.append(c); c = new char[1024]; } System.out.println("读取到的内容:" + sb); // 关闭流 isr.close(); is.close(); } /* * 测试输入字节流转向字符流 */ @Test public void OutputStreamTest() throws IOException { File file = new File("e://ww.txt"); if (!file.exists()) { file.createNewFile(); } OutputStream os = new FileOutputStream(file);// 字节流:不带缓冲----->字节流向字符流转化的中介 OutputStreamWriter osr = new OutputStreamWriter(os);// 字符流:带缓冲。但是输入流不带,输出流带。 String str = "这一块确实比较难,难以理解清楚。关键是找到字符和字节的区别、理清继承关系图以及两者直接的链接的桥梁。"; osr.write(str); osr.flush();// 刷新操作。 // 关闭流 osr.close(); os.close(); } }