javaSE基础学习笔记 day19
IO流
- 流的分类
① 按操作数据单位不同分为:字节流(8 bit) 字符流(16 bit)。
② 按数据流向不同分为:输入流 输出流。
③ 按流的角色不同分为:节点流(直接操作文件的流) 处理流(操作流的流)。
抽象基类 | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
注意:对于文本文件,一般使用字符流;对于非文本文件,一般使用字节流。
FileInputStream / FileOutputStream / FileReader / FileWriter
简介:节点流,直接作用在文件上。
使用实例(通过字节流来实现文件复制,字符流操作类似):
public void test() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//1.实例化File类的对象,指明要操作的文件
File f1 = new File("Hello.txt");
File f2 = new File("Hello1.txt");
//2.实例化指定的流
fis = new FileInputStream(f1);
//输出流第二个参数为是否追加,默认为false,覆盖原文件
fos = new FileOutputStream(f2, false);
//3.数据流的读写操作
byte[] buff = new byte[5];
int len;
while ((len = fis.read(buff)) != -1)
fos.write(buff, 0, len);
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭流资源
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
BufferedInputStream / BufferedOutputStream / BufferedReader / BufferedWriter
简介:缓冲流,内部提供了缓冲区,提高流的读取和写入速度。
使用实例:(通过字符流读取文件内容输出)
public void test1() {
BufferedReader br = null;
try {
//1.实例化File类的对象,指明要操作的文件
File f1 = new File("Hello.txt");
//2.实例化指定的流,节点流作为处理流构造器的参数
FileReader fr = new FileReader(f1);
br = new BufferedReader(fr);
//3.数据流的读操作
char[] cbuff = new char[5];
int len;
while ((len = br.read(cbuff)) != -1) {
String s = new String(cbuff, 0, len);
System.out.print(s);//此处输出文件内容
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
//4.关闭流资源
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注意:对于处理流的关闭,应先关闭外层流,再关闭内层流。但关闭外层流的同时,内层流也会自动关闭,故可省略。
InputStreamReader / OutputStreamWriter
简介:转换流,提供字节流与字符流之间的转换
InputStreamReader:将输入的字节流转换为输入的字符流。
OutputStreamWriter:将输出的字符流转换为输出的字节流。
使用实例:(将 UTF-8 编码的文件转化为 gbk 编码的文件)
public void test2(){
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
//1.实例化File类的对象,指明要操作的文件
File f1 = new File("Hello.txt");
File f2 = new File("Hello1.txt");
//2.实例化指定的流
FileInputStream fis = new FileInputStream(f1);
FileOutputStream fos = new FileOutputStream(f2);
isr = new InputStreamReader(fis,"UTF-8");
osw = new OutputStreamWriter(fos,"gbk");
//3.数据流的读写操作
char[] cbuff = new char[5];
int len;
while((len = isr.read(cbuff)) != -1){
osw.write(cbuff,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关闭流资源
if(isr != null){
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw != null){
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}