请问一下老师,我这样写对吗?
来源:3-14 缓冲流案例
qq_盗梦者_2
2017-09-14 22:34:09
package com.file;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Fileoutstream {
/**
* 实现图片的拷贝
*/
public static void main(String[] args) {
//一般在try catch块的外面定义流
FileInputStream in;
FileOutputStream out;
try {
//相对路径
in = new FileInputStream("test.png");
out = new FileOutputStream("newtest.png");
long startTime=System.currentTimeMillis();
byte b[] = new byte[1024];
int n = 0;
//每次从文件in中读入1024byte进入b中,在写入文件out
//当最后的字节数不满足1024时,通过返回n的字节数,写入到b中。
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
long endTime=System.currentTimeMillis();
System.out.println("消耗时间为:"+(endTime-startTime)+"毫秒");
//切记,操作完毕一定要记得关闭!!!
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedStream {
/**
* 缓冲流
*/
public static void main(String[] args) {
FileOutputStream fos;
BufferedOutputStream bos;
FileInputStream fis;
BufferedInputStream bis;
try {
fis = new FileInputStream("test.png");
bis = new BufferedInputStream(fis);
fos = new FileOutputStream("newtest1.png");
bos = new BufferedOutputStream(fos);
long startTime=System.currentTimeMillis();
int n;
while((n=bis.read())!=-1){
bos.write(n);
}
//缓冲池不满,不会进行写操作,
//flush()和close()都会清空内存
bos.flush();
long endTime=System.currentTimeMillis();
System.out.println("消耗时间为:"+(endTime-startTime)+"毫秒");
bos.close();
bis.close();
fis.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

第一个时用byte数组拷贝图片的时间,第二个是用缓冲流的时间,好像是快了一点,但是我不太明白为什么会快一些?是因为字节数组每次读取的写入的量没有缓冲区的大,还是因为文件操作是在硬盘而缓冲流是在内存中?
1回答
FileInputStream是字节流,BufferedInputStream是字节缓冲流。FileInputStream每次都是从硬盘读入,而BufferedInputStream大部分是从缓冲区读入。读取内存速度比读取硬盘速度快,因此通常情况下BufferedInputStream效率高。
相似问题