缓冲区的使用非常简单,就是
把需要使用缓冲区的流
,
作为参数
,
传进缓冲区的构造函数
即可。
1 缓冲区的出现,是为了提高流的操作效率而出现的
2 需要被提高效率的流,作为参数,传递给缓冲区的 构造函数
3 在缓冲区中,封装了一个数组,存入数据后,一次取出
1 字符流的缓冲区 :BufferedReader BufferedWreiter
BufferedReader:提供了一个一次读一行的方法readline,方便对文本数据的获取。
readline()只返回回车符前面的字符,不返回回车符。如果是复制的话,必须加入newLine(),写入回车符。
newLine()是java提供的多平台换行符写入方法,只有bufferedWrite能用,其他方法不能用
BufferedWriter 代码
/*
为了提高写入的效率。使用了字符流的缓冲区
创建了一个字符写入流的缓冲区对象,并和指定要被缓冲的流对象相关联
*/
BufferedWriter bw = new BufferedWriter(new FileWriter("buf.txt"));
//使用缓冲区的写入方法将数据先写入到缓冲区中
bw.write("asdfghjkl");
//使用缓冲区的刷新方法将数据刷目的地中
bw.flush();
// newLine() 只有bufferedWrite能用,其他方法不能用
bw.newLine(); // newLine()方法,自动给加一个换行符
bufw.write("xixiixii");
//关闭缓冲区。其实关闭的就是被缓冲的流对象
bw.close();
BufferedReader 代码
BufferedReader br = new BufferedReader(new FileReader("buf.txt"));
String line = null;
while((line=br.readLine()) != null){
System.out.println(line);
}
br.close();
综合使用 — 复制文本文件
BufferedReader br = new BufferedReader(new FileReader("buf.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("buf.txt"));
String line = null;
while( (line=bufr.readLine()) != null ){
bw.write(line);
bw.newLine();
bw.flush();
}
bw.close();
br.close();
2 字节流的缓冲区 :BufferedInputStream BufferedOutputStream
字节流缓冲区跟字符流缓冲区一样,也是为了提高效率
注意事项:1 read():会将字节byte()提升为int型值
2 write():会将int类型转换为byte()类型,保留最后的8位
代码练习
1 自己写一个 MyBufferedInputStream 缓冲类,提升复制速度
2 复制 MP3文件 1.MP3 —> 2.MP3
//自己的BufferedInputStream
class MyBufferedInputStream {
private InputStream in; //定义一个流对象
private byte [] buf = new byte[1024*4];
private int count = 0,pos = 0;
public MyBufferedInputStream(InputStream in){
this.in = in;
}
public int MyRead() throws IOException{
if(count==0) { //当数组里的数据为空时候,读入数据
count = in.read(buf);
pos = 0;
byte b = buf[pos];
count--;
pos++;
return b&255; //提升为int类型,在前面三个字节补充0。避免1111 1111 1111 1111
}else if(count > 0) {
byte b = buf[pos];
pos++;
count--;
return b&0xff; //提升为int类型,在前面三个字节补充0。避免1111 1111 1111 1111
}
return -1;
}
public void myClose() throws IOException{
in.close();
}
}
class BufferedCopyDemo {
public static void main(String[] args) {
long start = System.currentTimeMillis();
copy();
long end = System.currentTimeMillis();
System.out.println("时间:"+(end-start)+"ms");
start = System.currentTimeMillis();
copy1();
end = System.currentTimeMillis();
System.out.println("时间:"+(end-start)+"ms");
}
public static void copy1() { // 应用自己的缓冲区缓冲数据
MyBufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//匿名类,传入一个InputStream流对象
bis = new MyBufferedInputStream(new FileInputStream("1.mp3"));
bos = new BufferedOutputStream(new FileOutputStream("2.mp3"));
int buf = 0;
while((buf=bis.MyRead())!=-1) {
bos.write(buf);
}
}
catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("复制失败");
}
finally {
try {
if(bis!=null) {
bis.myClose();
bos.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}