1.缓冲流涉及到的类:
- BufferedInputStream
- BufferedOutputStream
- BufferedReader
- BufferedWriter
2.作用:
3.典型代码
3.1 使用BufferedInputStream和BufferedOutputStream:
@Test
public void testBufferedInputOutputStream(){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
// BufferedInputStream bis = new BufferedInputStream(new FileInputStream("灿烈.jpg"));该写法与下面的是同样的效果
bis = new BufferedInputStream(new FileInputStream(new File("灿烈.jpg")));
bos = new BufferedOutputStream(new FileOutputStream("灿烈2.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len = bis.read(buffer)) != -1){
bos.write(buffer,0,len);
}
System.out.println("复制成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.2 使用BufferedReader和BufferedWriter:
BufferedReader br = null;
BufferedWriter bw = null;
try {
//1.造文件
File file1 = new File("dbcp.txt");
File file2 = new File("dbcp1.txt");
//2.造流
//2.1造节点流
FileReader fr = new FileReader(file1);
FileWriter fw = new FileWriter(file2);
//2.2造缓冲流
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
//3.复制的细节:读取、写入
//读写操作
//方式一:使用char[]数组
// char[] cbuf = new char[1024];
// int len;
// while((len = br.read(cbuf)) != -1){
// bw.write(cbuf,0,len);
// }
//方式二:使用String
//readLine():一次读取字符文本文件的一行字
String data;
while((data = br.readLine()) != null){// 一次读取字符文本文件的一行字
//方法一:
// bw.write(data + "\n");
//方法二:
bw.write(data);// 一次写入一行字符,data中不包含换行符
bw.newLine();// 写入行分隔
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bw != null){
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
// fw.close();
// fr.close();
}
}