IO流
1、以单位来分: 字节流 - 字符流
2、以层级来分: 底层流 - 包装流
注意:
1、IO所有跟文件相关的流中, 构造方法中需要File作为参数的都可以使用文件路径直接取代
2、字节流写和读都是以字节为单位的,单个字节能不能正常显示出来, 是不确定的
字节流
InputStream / OutputStream - (通常用来做文件复制)
FileInputStream / FileOutputStream
1、构造方法
// FileInputStream
InputStream is = new FileInputStream(new File("a.txt"));
InputStream is1 = new FileInputStream("a.txt");
// FileOutputStream
OutputStream os = new FileOutputStream(new File("a.txt"));
OutputStream os1 = new FileOutputStream("a.txt");
// 在原有的文件末尾上追加内容
OutputStream os2 = new FileOutputStream("a.txt", true);
OutputStream os3 = new FileOutputStream(new File("a.txt"), true);
2、write/read
void write(int):
写入这个int值的低八位
int read():
读文件中一个字节, 并且存入int的低八位, 其余空位补0
当返回 -1 的时候, 说明文件读到了末尾
int read()/write() - 读/写单字节
/*
如果文件不存在, 会创建新的文件, 然后再写入内容
如果文件存在, 会清空原来的内容, 然后再写入
*/
OutputStream os = new FileOutputStream("a.txt");
// 以字节为单位写入, 只写入一个字节
// 00000000 00000000 00000001 00000000
os.write(256);
os.write(97); // 'a' = 97
os.write(65); // 'A' = 65
os.write(48); // '0' = 48
// 10000000 00000000 00000000 00000001
// 反:11111111 11111111 11111111 11111110
// 补:11111111 11111111 11111111 11111111
os.write(-1); // 11111111
// aA0�
/*
如果文件不存在, 就会抛出 FileNotFoundException
*/
InputStream is = new FileInputStream("a.txt");
// 读一个字节 8位 放入int的 32位 中的低八位, 其他空位都补0
int i ;
// 0 97 65 48 255
while((i = is.read()) != -1) {
System.out.println("i:" + i);
}
读写字节数组
注:返回 -1 标记着读到文件末尾
OutputStream os = new FileOutputStream("a.txt");
String str = "你好, 你吃了吗?";
// 字符串 -> 字节数组 [编码]
byte[] bs = str.getBytes("gbk");
// 等同于 os.write(bs);
os.write(bs, 0, bs.length);
os.write(bs, 2, 3); // 好,
//[-60, -29, -70, -61, 44, 32, -60, -29, -77, -44, -63, -53, -62, -16, 63]
System.out.println(Arrays.toString(bs));
InputStream is = new FileInputStream("a.txt");
byte[] bs = new byte[6];
int len ;
while((len = is.read(bs)) != -1) {
System.out.println("len: " + len);
// 如果读完了数组未满,剩余的元素与前一个数组相同
System.out.println("bs: " + Arrays.toString(bs));
}
BufferedInputStream / BufferedOutputStream (包装 — 高级流)
Buffered: 缓冲/缓存
构造方法
// 缓冲流是用字节流来包装的
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("a.txt"));
// API 就是 InputStream 的api
// 缓冲流是用字节流来包装的
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("a.txt"));
// API 就是 OutputStream 的api
文件复制
通过单个字节进行复制(最慢)
InputStream is = new FileInputStream("a.mp3");
OutputStream os = new FileOutputStream("a_bak.mp3");
int i ;
// 读的同时 写入到另一个文件
long time1