I/O 框架
1 流的概念
内存与存储设备之间传输数据的通道
2 流的分类
2.1 按方向【重点】
- 输入流:将<存储设备>中的内容读到<内存>中
- 输出流:将<内存>中的内容写到<存储设备>中
2.2 按单位
- 字节流:以字节为单位,可以读写所有数据
- 字符流:以字符为单位,只能读写文本数据
2.3 按功能
- 节点流:具有实际传输数据的读写功能
- 过滤流:在节点流的基础之上增强功能
3 字节流
下面两个为字节流的父类(抽象类)
//InputStream 字节输入流
public int read(){
}
public int read(byte[] b){
}
public int read(byte[] b, int off, int len){
}
// OutputStream 字节输出流
public void write(int n){
}
public void write(byte[] b){
}
public void write(byte[] b, int off, int len){
}
3.1 文件字节流
文件输入流
psvm(String[] args) throws Exception{
// 1 创建FileInputStream 并指定文件路径
FileInputStream fis = new FileInputStream("d:\\abc.txt");
// 2 读取文件
// fis.read();
// 2.1单字节读取
int data = 0;
while((data = fis.read()) != -1){
sout((char)data);
}
// 2.2 一次读取多个字节
byte[] buf = new byte[3]; // 大小为3的缓存区
int count = fis.read(buf); // 一次读3个
sout(new String(buf));
sout(count);
int count2 = fis.read(buf); // 再读3个
sout(new String(buf));
sout(count2);
// 上述优化后
int count = 0;
while((count = fis.read(buf)) != -1){
sout(new String(buf, 0, count));
}
// 3 关闭
fis.close();
}
文件输出流
psvm(String[] args) throws Exception{
// 1 创建文件字节输出流
FileOutputStream fos = new FileOutputStream("路径", true);// true表示不覆盖 接着写
// 2 写入文件
fos.write(97);
fos.write('a');
// String string = "hello world";
fos.write(string.getByte());
// 3 关闭
fos.close();
}
3.2 图片复制案例
// 1 创建流
// 1.1 文件字节输入流
FileInputStream fis = new FileInputStream("路径");
// 1.2 文件字节输出流
FileInputStream fos = new FileOutpuStream("路径");
// 2 边读边写
byte[] buf = new byte[1024];
int count = 0;
while((count = fis.read(buf)) != -1){
fos.write(buf, 0, count);
}
// 3 关闭
fis.close();
fos.close();
3.3 字节缓冲流
缓冲流:BufferedInputStream / BufferedOutputStream
- 提高IO效率,减少访问磁盘次数
- 数据存储在缓冲区中,flush是将缓冲区的内容写入文件中,也可以直接close
// 使用字节缓冲流 读取 文件
psvm(String[] args) throws Exception{
// 1 创建BufferedInputStream
FileInputStream fis = new FileInputStream("路径");
BufferedInputStream bis = new BufferedInputStream(fis); //缓冲区默认大小:8192=8kb
// 2 读取
int data = 0;
while((data = bis