- 定义缓冲数组进行文件复制
public class CopyDemo1 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("Kalimba/.mp3");
FileOutputStream fos = new FileOutputStream("Kaliba2.mp3");
//创建一个10k的缓存
byte[] data = new byte[1024*10];
int len;
long s = System.currentTimeMillis();
while ((len=fis.read(data))!=-1){
fos.write(data,0,len);
}
long e = System.currentTimeMillis();
System.out.println("over"+(e-s));
fis.close();
fos.close();
}
}
- 使用缓冲流无需定义数组,加快效率
高级流需要依赖低级流,低级流就相当于一根什么的输液管,高级流就是输液管上的卡子,有其他功能所以高级。
public class CopyDemo2 {
public static void main(String[] args) throws IOException {
//高级流不能直接指向文件,它创建时需要低级流对象
FileInputStream fis = new FileInputStream("Ka.mp3"); //低级流指向对象
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream("Ka.mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int d;
long s = System.currentTimeMillis();
while((d=bis.read())!=-1){
bos.write(d);
}
long e = System.currentTimeMillis();
System.out.println("over"+(e-s));
bis.close();
bos.close();//只关高级流,低级流联动自动关
}
}
void flush();
强制将当前缓冲区中的字节一次性写出
同时清空缓冲区,是即时的写出
实际上也会增加写出的次数,降低写出效率
调用close前会自动调用flush,所以flush调用不必须。