IO流的分类,站在不同的角度,分类方式是不一样的:
1)根据流向划分:输入流和输出流;
2)根据数据的单位划分:字节流和字符流;
3)根据功能的划分:节点流和包装流
四大基流(字节输出流OutputStream、字节输入流InputStream、字符输出流Writer、字符输入流Reader)
四大基流都是抽象类:其他流都是继承于这四大基流。
我们不能创建四大基流的对象,只能创建其子类对象。
无论什么流,都有close()方法,用来关闭资源。
根据数据的单位划分:(以下是字节流的体系)
以下是字符流体系:
操作IO流的模板:
1)创建源或者目标对象:
拿文件流举例:
输入操作:把文件中的数据流向到程序中,此时文件就是源,程序就是目标;
输出操作:把程序中的数据流向到文件中,此时文件就是目标,程序就是源。
2)创建IO流对象:
输入操作:创建输入流对象
输出操作:创建输出流对象
3)具体的IO操作:
输入操作:输入流对象的read()方法
输出操作:输出流对象的write()方法
4)关闭资源:
输入操作:输入流对象.close()
输出操作:输出流对象.close()
操作IO流的六字箴言:读进来,写出去
读进来:进来强调的是输入,读说明是read方法
写出去:出去强调的是输出,写说明是write方法
文件流:顾名思义,程序和文件打交道,此时我们谈及的文件,指的是纯文本文件(txt的,不要使用woed或者excel)
FileInputStream:文件的字节输入流
FileOutputStream:文件的字节输出流
FileReader:文件的字符输入流
FileWriter:文件的字符输出流
字节流和字符流的选择:
一般的,操作二进制文件(图片、音频、视频等)必须使用字节流;
一般的,操作文本文件使用字符流;
如果不清楚哪一类文件,就使用字节流。
文件字节流:(test1()是之前的正常规范方法,test2()是Java7之后所提供的的方法)
FileInputStream:文件的字节输入流
FileOutputStream:文件的字节输出流
public class FileDemo2 {
public static void main(String[] args) {
// test1();
test2();
}
/*
* 在Java7之后,提供的自动资源关闭
*/
private static void test2() {
// 1、创建源和目标
File srcFile = new File("file/ch.txt");
File destFile = new File("file/ch_copy.txt");
try(
//打开资源的代码
// 2、创建输入流和输出流对象
InputStream in = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(destFile);
)
{
//可能出现异常的代码
// 3、读和写的操作
byte[] buffer = new byte[1024];
int len = -1;
while ((len = in.read(buffer)) != -1) {
//打印一下读取的数据
out.write(buffer, 0, len);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private static void test1() {
//声明资源对象
InputStream in = null;
OutputStream out = null;
try {
// 1、创建源和目标
File srcFile = new File("file/ch.txt");
File destFile = new File("file/ch_copy.txt");
// 2、创建输入流和输出流对象
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
// 3、读和写的操作
byte[] buffer = new byte[1024];//一次性可读1024个字节
int len = -1;//表示已经读取的字节数,在底层规定是-1读取到末尾
while ((len = in.read(buffer)) != -1) {
//打印一下读取的数据
out.write(buffer, 0, len);
}
} catch (IOException e) {
//处理异常
e.printStackTrace();
}finally{
// 4、关闭流(为了出现不必要的异常,各关各的)
try {
if(in!=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(out!=null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件字符流:
FileReader:文件的字符输入流
FileWriter:文件的字符输出流
//文件的字符流
public class CopyFile {
public static void main(String[] args) throws Exception {
// 1创建源和目标对象
File srcFile = new File("file/ch.txt");
File destFile = new File("file/ch_copy.txt");
// 2创建输入流和输出流对象
Reader in = new FileReader(srcFile);
Writer out = new FileWriter(destFile);
// 3读和写的操作
char[] buffer = new char[100];
int len = -1;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// 4关闭流
in.close();
out.close();
}
}