Java基础 Day22
一、IO 流
1、简介
I:Input(输入,读取)
O:Output(输出,写出)
主要用途:数据传输
2、体系结构
(1)字节流(万能流)
抽象类:InputStream(字节输入流)、OutputStream(字节输出流)
抽象类的子类:FileInputStream、FileOutputStream
用字节流操作纯文本文件时可能出现乱码
(2)字符流(操作纯文本文件)
抽象类:Reader(字符输入流)、Writer(字符输出流)
抽象类的子类:FileReader、FileWriter
二、FileOutputStream 字节输出流
1、构造方法
FileOutputStream(String name) | |
FileOutputStream(String name, boolean append) | |
FileOutputStream(File file) | |
FileOutputStream(File file, boolean append) |
2、常用方法
void write(int b) | |
void write(byte[] b) | |
void write(byte[] b, int off, int len) |
FileOutputStream f1 = new FileOutputStream("./day22/src/t1.txt");
f1.write(97);
byte[] arr = {97, 98, 99};
f1.write(arr);
f1.write("\nHello World\n".getBytes());
f1.write("Hello Java\n".getBytes());
f1.close();t1.txt 的内容:
aabc
Hello World
Hello Java
3、注意事项
关联的文件如果不存在,自动创建;如果存在,默认是覆盖写入
流对象使用完后,要用close方法关流,防止占用资源
4、标准的关流代码
JDK7之后
try () 中的对象, 需要实现过 AutoCloseable 接口
try (需要调用close方法的对象) {逻辑代码...
} catch (异常类名 对象名) {异常的处理方式
}// 会自动调用close方法 try (FileOutputStream f2 = new FileOutputStream("./day22/src/t2.txt")) {f2.write("Hello World\n".getBytes());
} catch (IOException e) {e.printStackTrace();
}
三、FileInputStream 字节输入流
1、构造方法
FileInputStream(String name) | |
FileInputStream(File file) |
关联的文件不存在会抛出 FileNotFoundException 异常
文件夹的话会拒绝访问
2、常用方法
int read() | |
int read(byte[] b) | 返回读取到的有效字节个数 |
将读到的内容转换为字符串,用String 类的一个构造方法
public String | 将字节数组转换为字符串 参数2 : 起始索引 |
四、字节缓冲流
字节缓冲流在源代码中内置了字节数组,可以提高读写效率
BufferedInputStream(InputStream in) | |
BufferedOutputStream(OutputStream out) |
注意: 缓冲流不具备读写功能, 它们只是对普通的流对象进行包装
真正和文件建立关联的, 还是普通的流对象
原理:读入时一次读入8192个字节将内置数组装满再一并读入
输出时写出8192个字节将内置数组装满再一并写出(close方法会检查内置数组)
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("./day22/src/t1.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("./day22/src/t3.txt"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes)) != -1) {bos.write(bytes, 0, len);
}
bis.close();
bos.close();
五、字符集和字符编码
1、字符集
字符集是指多个字符的集合
常用的有GBK、Unicode等字符集
2、字符编码
字符编码是指一种映射规则
根据这个规则可以将某个字符映射成其他形式的数据以便在计算机中存储和传输
GBK:每个中文占用2个字节
Unicode:每个中文占用3个字节(有UTF-32、UTF-16、UTF-8等编码方式)
编码指字符转字节,解码指字节转字符
中文字节以负数开头
六、FileReader 字符输入流
1、构造方法
FileReader(String fileName) | |
FileReader(File file) |
2、常用方法
public int read() | |
public int read(char[] cbuf) |
七、FileWriter 字符输出流
1、构造方法
FileWriter(String fileName) | |
FileWriter(String fileName, boolean append) | |
FileWriter(File file) | |
FileWriter(File file, boolean append) |
2、常用方法
public void write(int c) | |
public void write(char[] cbuf) | |
public write(char[] cbuf, int off, int len) | |
public void write(String str) | |
public void write(String str, int off, int len) |
字符输出流写出数据,需要调用flush或close方法,数据才会写出
Flush后可以继续写出,Close 后不能继续写出