public class BufferedTest { public static void main(String[] args) { FileOutputStream fos = null; FileOutputStream fos2 = null; BufferedOutputStream bos = null; try { fos = new FileOutputStream("fix.txt"); long start=System.currentTimeMillis(); for ( int i=0 ; i<=100000; i++ ) { fos.write('a'); } long end = System.currentTimeMillis(); System.out.println("fix.txt不用缓冲流写"); long time1 =(end-start); System.out.println("用时"+time1); bos = new BufferedOutputStream(fos2); long start2=System.currentTimeMillis(); for ( int i=0 ; i<=100000; i++ ) { bos.write('a'); } // bos.write('a'); long end2 = System.currentTimeMillis(); long time2 =(end2-start2); System.out.println("fox.txt用缓冲流写"); System.out.println("用时"+time2); System.out.println("节约时间"+(time1-time2)); // bos.flush(); fos.close(); fos2.close(); bos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
fos2 这个变量没有进行初始化,所以在使用的时候报了空指针异常,fos2 初始化一下就好,就像你的fos变量一样:fos =
new
FileOutputStream(
"fix.txt"
);