为什么我用了缓冲流更慢了
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class test4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
File f1 = new File("one.txt");
File f2 = new File("two.txt");
try {
f1.createNewFile();
f2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis1 = new FileInputStream("world.txt");
FileInputStream fis = new FileInputStream("world.txt");
FileOutputStream fos1 = new FileOutputStream("one.txt");
FileOutputStream fos2 = new FileOutputStream("two.txt");
BufferedInputStream bis = new BufferedInputStream(fis1);
BufferedOutputStream bos = new BufferedOutputStream(fos2);
int n = 0;
byte[] b = new byte[1024];
//用缓冲流
long timestart2 = System.currentTimeMillis();
while ((n = bis.read(b)) != -1) {
bos.write(b, 0, n);
}
long timeend2 = System.currentTimeMillis();
bos.flush();
//不用缓冲流
long timestart1 = System.currentTimeMillis();
while ((n = fis.read(b)) != -1) {
fos1.write(b, 0, n);
}
long timeend1 = System.currentTimeMillis();
System.out.println("one不使用缓冲流来写");
System.out.println("用时为:" + (timeend1 - timestart1));
System.out.println("two使用缓冲流来写");
System.out.println("用时为:" + (timeend2 - timestart2));
System.out.println("用缓冲流来写节省了:" + ((timeend1 - timestart1) - (timeend2 - timestart2)));
fis1.close();
fos1.close();
fos2.close();
bis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
正在回答 回答被采纳积分+1
根据提议,建议同学在写入流的时候可以这样做,如下,使用FileOutputStream、BufferedOutputStream这两个流就可以了,代码会简洁明了些。
int n = 0; byte[] b = new byte[100000]; //用缓冲流 long timestart2 = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { b[i] = (byte) (1 + Math.random() * 99); bos.write(b[i]); } long timeend2 = System.currentTimeMillis(); bos.flush(); //不用缓冲流 long timestart1 = System.currentTimeMillis(); byte[] letter2 = new byte[100000]; for (int i = 0; i < 100000; i++) { letter2[i] = (byte) (1 + Math.random() * 99); fos1.write(letter2[i]); } long timeend1 = System.currentTimeMillis();
祝学习愉快~
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星