写文件 faster and faster


import java.io.BufferedWriter;
import java.io.FileWriter;

public class Test {

public static void main(String[] args) {
int max = 100000000;
long t1 = System.currentTimeMillis();
test1(max);
long t2 = System.currentTimeMillis();
System.out.println("test1耗时:"+(t2-t1));
long t3 = System.currentTimeMillis();
test2(max);
long t4 = System.currentTimeMillis();
System.out.println("test2耗时:"+(t4-t3));
long t5 = System.currentTimeMillis();
test3(max);
long t6 = System.currentTimeMillis();
System.out.println("test3耗时:"+(t6-t5));

//两次测试结果
//已知 max=100000000

//test1耗时:46593/52906
//test2耗时:28563/28250
//test3耗时:21859/22594
}

public static void test1(int max){
BufferedWriter bw = null;
String fileName = "d:/1.txt";
try{
bw = new BufferedWriter(new FileWriter(fileName, true));
for(int i=0;i<max;i++){
bw.write(i+"\r\n");
}
bw.flush();
bw.close();
}catch (Exception e) {
e.printStackTrace();
}
}

public static void test2(int max){
BufferedWriter bw = null;
String fileName = "d:/2.txt";
try{
bw = new BufferedWriter(new FileWriter(fileName, true));
for(int i=0;i<max;i++){
bw.write(String.valueOf(i));
bw.write("\r\n");//快于bw.newLine()
}
bw.flush();
bw.close();
}catch (Exception e) {
e.printStackTrace();
}
}

public static void test3(int max){
BufferedWriter bw = null;
String fileName = "d:/3.txt";
try{
StringBuffer sb = new StringBuffer();
bw = new BufferedWriter(new FileWriter(fileName, true));
for(int i=0;i<max;i++){
sb.append(i);
sb.append("\r\n");
//10000写入一次
if(i%10000==0){
bw.write(sb.toString());
sb.delete(0, sb.length());
}
}
bw.write(sb.toString());
bw.flush();
bw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}

备注:test1采用字符串连接的写入方式,一次写入一行,耗时最长;test2采用分别写入方式,耗时近1半;test3采用批量写入耗时不足一半。由此可知,test3的写入效率最高。

//两次测试结果
//已知 max=100000000

//test1耗时:46593/52906
//test2耗时:28563/28250
//test3耗时:21859/22594

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值