45 IO流
原理:
I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。 Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行。 java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
流的分类:
-
按操作数据单位不同分为:字节流(8 bit),字符类流(16 bit)
-
按数据流的流向不同分为:输入流,输出流
-
按流的角色不同分为:节点流,处理流
抽象基类 字节流 字符类
输入流 InputSream Reader
输出流 OutputStream Writer
-
对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
-
对于非文本文件(.jpg,.mp3,.avi,.mp4,.ppt,.....),使用字节流处理
FileReader
FileReader(char[] cbuf)
将day04的hello.txt文件内容读入程序中,并输出到控制台
说明点:
-
read(): 返回读入的一个字符。如果达到文件末尾,返回-1
-
异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally
-
读入的文件一定要存在,否则会报FileNotFoundException
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");//相较于当前module
//2.提供具体的流
FileReader fr = new FileReader(file);
//3.数据的读入
//read(): 返回读入的一个字符。如果达到文件末尾,返回-1
//方式一:
int date = fr.read();
while (date != -1){
System.out.print((char)date);
date = fr.read();
}
//方式二:语法上针对于方式一的修改
FileReader fr = null;
try {
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");//相较于当前module
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入
//read(): 返回读入的一个字符。如果达到文件末尾,返回-1
//方式一:
// int date = fr.read();
// while (date != -1){
// System.out.print((char)date);
// date = fr.read();
// }
//
//方式二:语法上针对于方式一的修改
int data;
while((data = fr.read()) != -1){
System.out.println((char)data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流的关闭
try {
if(fr != null){
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
int data;
while((data = fr.read()) != -1){
System.out.println((char)data);
}
//4.流的关闭
fr.close();
加强版
read(char[] cbuf):返回每次读入cbuf数组的字符个数。如果达到文件末尾,返回-1
FileReader fr = null;
try {
//1.File类的实例化
File file = new File("hello.txt");
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
//read(char[] cbuf):返回每次读入cbuf数组的字符个数。如果达到文件末尾,返回-1
char[] cbuf = new char[5];
int len;
while((len = fr.read(cbuf)) != -1){
//方式一:
//错误的写法
// for(int i =0; i < chuf.length ; i++){
// System.out.println(cbuf[i]);
// }
// }
//正确的写法
// for(int i =0; i < len ; i++){
// System.out.println(cbuf[i]);
// }
//方式二:
//错误的写法:对应着方式一的写法
// String str = new String(cbuf);
// System.out.println(str);
//正确的写法
String str = new String(cbuf,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fr != null) {
//4.资源的关闭
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileWriter
FileWriter(cbuf,0,len)
从内存中写出数据到硬盘的文件里
说明:
-
输出操作,对应的File可以不存在的,并不会报异常。
-
File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
File对应的硬盘中的文件如果存在:
如果流使用的构造器是:FileWriter(file,false) / FileWriter(file) :对原有文件的覆盖;
如果流使用的构造器是:FileWriter(file,true):不会对原有文件基础上覆盖,而是在原有的文件上追加内容。
通过FileReader和FileWriter实现文本的复制
FileInoutOutputStream
FileInputStream(byte[] buffer)
FileOutputStream(byte[] buffer,0,len)
实现对图片的复制
缓冲流
处理流之一:缓存流
BufferedInputStream(byte[] buffer)
BufferedOnputStream(byte[] buffer,0,len)
作用:提高流的读取,写入的速度
处理流就是“套接”在已有流的基础上
public class BufferedTest {
BufferedReader(char[] cbuf)
BufferedWriter(char[] cbuf,0,len)
实现对文本的复制
图片的加密