IO流
IO流可以根据流的大小分为字节流和字符流
(1)字节流(只能一个字节一个字节操作)
字节流不支持中文
输出流
常用的有OutputStream out = new FileOutputStream(File file)或OutputStream out = new FileOutputStream(String name)
例1:

执行完操作后一定要.close()(默认实现了flush)或者
先.flush()再.close()
例2:

在原来的内容基础上添加内容:
OutputStream out = new FileOutputStream(String name, true)

输入流
常用的有InputStream in = new FileInputStream(File file)或InputStream in = new FileInputStream(String name)
例1:使用.read()方法对内容进行读取(只能读取一个字节)

例2:对所有内容进行读取:

使用输入流和输出流拷贝文件

由于以上拷贝方法速度较慢,可以使用缓存(buffer)来提高速度
例:

字节流包装类
BufferedInputStream
继承于FilterInputStream
使用了缓存
ByteArrayInputStream
会创建一个字节数组缓存
DataInputStream
可以根据类型读取
FilterInputStream
过滤
继承于InputStream
PushbackInputStream
应用
使用流生成图片
例:


(2)字符流
字符流支持中文
字符流实际上是字节流的包装流
1)Writer

PrintWriter可以完成字节流字符流的相互转换
2)Reader

try with resources
在IO流中使用 try with resources 来处理异常可以自动关闭流。
try(定义对象){检查异常
}catch(IOException e){
}
例:

16万+

被折叠的 条评论
为什么被折叠?



