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("输出流测试文件 \r\n".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("输出流测试文件\r\n".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("输出流测试文件\r\n"); } 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("流关闭异常!"); } } }
运行结果: