一、流的分类
- 操作数据单位:字节流,字符流
- 数据的流向:输入流、输出流
- 流的角色:节点流、处理流
二、流的体系结构
抽象基类 | 节点流(文件流) | 缓冲流(处理流的一种) |
---|---|---|
InputStream | FileInputStream | BufferedInputStream |
OutputStrem | FileOutputStream | BufferedOutputStream |
Reader | FileReader | BufferedReader |
Writer | FileWriter | BufferedWriter |
三、FileReader
将day09下的hello.txt文件内容读入到程序中,并输出到控制台
说明点:
- read()的理解:返回读入的一个字符。如果达到文件末尾
- 异常的处理:为了保证流资源一定可以执行关闭的操作。需要使用try—catch-finally
- 读入的文件一定要存在,否则就会报FileNotFoundException。
@Test
public void testFileReader() {
//1.实例化File类的对象,指明操作的文件
File file=new File("hello.txt");//相较于当前Module
//2.提供具体的流
FileReader fr= null;
try {
fr = new FileReader(file);
//3.数据的读入过程
//read():返回读入的一个字符,如果达到文件末尾了,返回-1
int data = fr.read();
while(data!=-1){
System.out.print((char) data);
data =fr.read();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//4.流的关闭操作
try {
if(fr!=null){
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//read()操作升级:使用read的重载方法
@Test
public void test1() {
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 <cbuf.length ; i++) {
// System.out.print(cbuf[i]);helloworld123ld
// }
//正确的写法:
for (int i = 0; i < len; i++) {
System.out.print(cbuf[i]);//helloworld123
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fr!=null)
//4.资源的关闭
{
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
四、FileWriter
从内存中写出数据到硬盘的文件里
说明:
- 输出操作,对应的File文件可以不存在。并不会报异常
- File对应的文件如果不存在,在输出的过程中,会自动创建此文件。
如果存在:
- 如果流使用的构造器是FileWriter(file,false)或FileWriter(file):对原有文件的覆盖。
- 如果流使用的构造器是FileWriter(file,true),就不会覆盖原有文件,而是对原有文件基础上追加内容。
@Test
public void test2() throws IOException {
//1.提供File类的对象,指明写出到的文件
File file =new File("hello1.txt");
//2.提供FileWriter的对象,据的写出
FileWriter fw=new FileWriter(file);
//3.写出的操作
fw.write("I have a dream!\n");
fw.write("You need to have a dream!");
//4.流资源的关闭
fw.close();
}
五、将一个文件内容写入另一个文件
//将一个文件内容写入另一个文件
@Test
public void test3() {
FileReader fr= null;
FileWriter fw= null;
try {
File file = new File("hello.txt");
File file1 = new File("hello1.txt");
fr = new FileReader(file);
fw = new FileWriter(file1,true);
char[] cbuf=new char[5];
int len;
while ((len=fr.read(cbuf))!=-1){
fw.write(cbuf);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fr!=null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fw!=null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}