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 = System.cu

本文详细介绍了Java中的IO流,包括字节流(InputStream/OutputStream及其子类如FileInputStream/FileOutputStream)、字符流(Reader/Writer及BufferedReader/PrintWriter)、对象流(ObjectInputStream/ObjectOutputStream)。讨论了各种流的构造方法、读写操作,并提到了文件复制、加密解密以及使用Properties处理属性集。此外,还提及了RandomAccessFile类用于对文件的随机访问。
&spm=1001.2101.3001.5002&articleId=107720060&d=1&t=3&u=d436f4bd5dd3488e88996f933849f395)
1313

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



