「这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战」
IO流
IO流的概述
I 表示input 是数据从硬盘进内存的过程,称之为读。 O 表示output 是数据从内存到硬盘的过程,称之为写。
思考一个问题?
在数据传输的过程中,是谁在读?是谁在写?这个参照物是谁?
IO的数据传输,可以看做是一种数据的流动, 按照流动的方向, 以内存为参照物,进行读写操作。
简单来说:内存在读,内存在写。
IO 流的技术选型
什么是纯文本文件?
字节流:
字节流写数据:
public class OutputDemo {
public static void main(String[] args) throws IOException {
//1. 创建字节输出流的对象 --- 告诉虚拟机我要往哪个文件中写数据了。
FileOutputStream fos = new FileOutputStream("D:\a.txt");
// FileOutputStream fos = new FileOutputStream(new File("D:\a.txt"));
//2. 写数据
fos.write(97);
//3. 释放资源
fos.close();
}
}
字节流写数据: 步骤:
- 创建字节输出流对象。
注意事项: 如果文件不存在,就创建。 如果文件存在就清空。
- 写数据
注意事项: 写出的整数,实际写出的是整数在码表上对应的字母。
- 释放资源
注意事项: 每次使用完流必须要释放资源。
public class OutputDemo2 {
public static void main(String[] args) throws IOException {
//1.创建字节输出流的对象
//注意点:如果文件不存在,会帮我们自动创建出来.
// 如果文件存在,会把文件清空.
FileOutputStream fos = new FileOutputStream("C:\\itheima\\a.txt");
//2,写数据 传递一个整数时,那么实际上写到文件中的,是这个整数在码表中对应的那个字符.
fos.write(98);
//3,释放资源
fos.close(); //告诉操作系统,我现在已经不要再用这个文件了.
}
}
public class OutputDemo3 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("bytestream\a.txt");
fos.write(97);
fos.write(98);
fos.write(99);
fos.close();
}
}
public class OutputDemo4 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("bytestream\a.txt");
byte[] bys = {97,98,99,100,101};
fos.write(bys);
// fos.write(bys,1,2);
fos.close();
}
}
字节流写数据加try catch 异常处理
public class OutputDemo6 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
System.out.println(2/0);
fos = new FileOutputStream("D:\a.txt");
fos.write(97);
}catch (Exception e){
e.printStackTrace();
}finally {
// finally 语句里面的代码,一定会被执行
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
小结:
步骤:
- 创建字节输出流对象
文件不存在,就创建。 文件存在就清空,如果不想被清空则加true。
- 写数据:
可以写一个字节,写一个字节数组,写一个字节数组的一部分。
写一个回车换行:\r\n
- 释放资源
字节流读数据(一次读一个字节)
public class OutputDemo7 {
public static void main(String[] args) throws IOException {
// 如果文件存在,那么就不会报错。
// 如果文件不存在,那么就直接报错
FileInputStream fis = new FileInputStream("bytestream\a.txt");
int read = fis.read();
// 一次读取一个字节,返回值就是本次读到的那个字节数据。
// 也就是字符在码表中对应的哪个数字。
// 如果我们想要看到的是字符数据,那么一定要强转成char
System.out.println(read);
// 释放资源
fis.close();
}
}
读取文件中多个字节的代码:
public class OutputDemo8 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("bytestream\a.txt");
//1. 文件中多个字节我怎么办?
int b;
while ((b = fis.read()) != -1){
System.out.println(b);
}
fis.close();
}
}
public class OutputDemo9 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("c:\a.avi");
FileOutputStream fos = new FileOutputStream("bytestream:\a.avi");
int b;
while ((b = fis.read()) !=1){
fos.write(b);
}
fis.close();
fos.close();
}
}