FileOutputStream,BufferedOutputStream,FileWriter 效率比较
测试代码:
/** * 写文件 * FileOutputStream, BufferedOutputStream, FileWriter * 三个流 效率比较 */ @Test public void writeFile() throws Exception { FileOutputStream out = null; FileOutputStream outSTr = null; BufferedOutputStream Buff = null; FileWriter fw = null; int count = 999;//写文件行数 try { //FileOutputStream out = new FileOutputStream(new File("F:/FileOutputStream.txt")); long begin = System.currentTimeMillis(); for (int i = 0; i < count; i++) { out.write("输出流测试文件 ".getBytes()); } out.close(); long end = System.currentTimeMillis(); System.out.println("FileOutputStream执行耗时:" + (end - begin) + " 毫秒"); //BufferedOutputStream outSTr = new FileOutputStream(new File("F:/BufferedOutputStream.txt")); Buff = new BufferedOutputStream(outSTr); long begin0 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { Buff.write("输出流测试文件 ".getBytes()); } Buff.flush(); Buff.close(); long end0 = System.currentTimeMillis(); System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0) + " 毫秒"); //FileWriter 字符流 fw = new FileWriter("F:/FileWriter.txt"); long begin3 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { fw.write("输出流测试文件 "); } fw.close(); long end3 = System.currentTimeMillis(); System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 毫秒"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); Buff.close(); outSTr.close(); out.close(); } catch (Exception e) { throw new Exception("流关闭异常!"); } } }
运行结果:
FileOutputStream执行耗时:7 毫秒 BufferedOutputStream执行耗时:2 毫秒 FileWriter执行耗时:4 毫秒