目录
一、IO流
1.IO流的目的
- 写数据:将数据写到文件中,实现数据永久化保存
- 读数据:读取文件中已经存在的数据
2.IO的表示
I表示Input,数据从硬盘进内存的过程,称之为读
O表示Output,数据从内存到硬盘的过程,称之为写
(按照流的方向,是以内存为参照物再进行读写的)
二、IO流的分类
1.按流向分
- 输入流:读数据(数据从硬盘流向内存)
- 输出流:写数据(数据从内存流向硬盘)
2.按数据类型分
- 字节流:可以操作所有类型的文件(包括音频、视频、图片等)
- 字符流:只能操作纯文本文件(包括Java文件、txt文件等)
(纯文本文件:用记事本打开能读得懂的,就是纯文本文件)
三、字节流(ByteStream)
1.字节流写数据
步骤:1.创建字节输出流的对象 2.写数据 3.释放资源
代码演示:
public class byteStreamDemo_01 {
public static void main(String[] args) throws IOException {
//1.创建字节输出流对象
FileOutputStream fos = new FileOutputStream("D:\\a.txt");
//2.写数据
fos.write(97);
//3.释放资源
fos.close();
}
2.字节流的注意事项
- 如果文件不存在,它会自动创建出来
- 如果文件是存在的,它会把文件清空
- 写入的整数,对应码表中的字符
3.字节流写数据的三种方式
- void write(int b) 一次只写一个字节数据
- void write(byte[] b) 一次写一个字节数组数据
- void write(byte[] b,int off,int len) 一次写一个字节数组的部分数据(第一个参数是数组名,第二个参数是从哪个索引开始写,第三个参数代表写几个)
代码示例:
public class byteStreamDemo_03 {
public static void main(String[] args) throws IOException {
//1.创建字节输出流对象
FileOutputStream fos = new FileOutputStream("myByteStream\\a.txt");
//2.写数据
byte[] bys = {97, 98, 99, 100, 101, 102, 103};
//第一个参数是数组名,第二个参数是从哪个索引开始写,第三个参数代表写几个
fos.write(bys, 1, 2);
//3.释放资源
fos.close();
}
4.字节流写数据的两个问题
(1)字节流写数据如何换行?
写完数据后加换行符:
windows:\r\n
Linux:\n
mac:\r
代码示例:
public class byteStreamDemo_04 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("myByteStream\\a.txt");
fos.write(97);
fos.write("\r\n".getBytes());
fos.write(98);
fos.write("\r\n".getBytes());
fos.write(99);
fos.write("\r\n".getBytes());
fos.write(100);
fos.write("\r\n".getBytes());
fos.write(101);
fos.close();
}
(2)字节流写数据如何实现追加写入?
在创建文件输出流已指定的名称写入文件,第二个参数为续写开关,若写true,则打开续写开关,不会清空文件里面的内容,默认为false关闭
代码演示:
public class byteStreamDemo_05 {
public static void main(String[] args) throws IOException {
//在第二个参数是续写开关,写入true表示打开续写,默认是false关闭
FileOutputStream fos = new FileOutputStream("myByteStream\\a.txt", true);
fos.write(97);
fos.write(98);
fos.write(99);
fos.write(100);
fos.write(101);
fos.close();
}
5.字节流try catch异常捕获
public class byteStreamDemo_06 {
public static void main(String[] args) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("D:\\a.txt");
fos.write(97);
} catch (IOException e) {
e.printStackTrace();
} finally {
//finally里面的代码一定会被执行
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}