1.FileOutputStream方式
2.BufferedOutputStream方式
3.FileWriter方式
经过多次测试,发现不缓存的FileOutputStream会比较慢,当文件小的话,关系不大,但是当文件大时,消耗的时间就会有很明显差别
package fileTest; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; /** * 三种文件写入方式 * */ public class OutputFile1 { public static void main(String[] args) { FileOutputStream out = null; FileOutputStream outStr = null; BufferedOutputStream buff =null; FileWriter fw = null; int count = 1000; try { out = new FileOutputStream(new File("D:\\testFile\\test.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)); outStr = new FileOutputStream(new File("D:\\testFile\\test1.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)); fw = new FileWriter(new File("D:\\testFile\\test2.txt")); long begin1 = System.currentTimeMillis(); for(int i=0; i<count; i++){ fw.write("测试文件操作\r\n"); } fw.close(); long end1 = System.currentTimeMillis(); System.out.println("FileWriter方式耗时:"+(end1-begin1)); } catch (Exception e) { // TODO: handle exception }finally { try { fw.close(); buff.close(); outStr.close(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
运行结果:
FileOutputStream方式耗时6
BufferedOutputStream方式耗时:5
FileWriter方式耗时:4
时间: 2024-11-10 14:03:19