写大文件

1)使用BufferedWriter写文件。一亿条记录

 1 package nioTest;
 2 import java.io.BufferedWriter;
 3 import java.io.FileWriter;
 4 import java.io.IOException;
 5 import java.util.Random;
 6 
 7 public class nio {
 8     public static void writeBigFile() throws IOException{
 9         
10         @SuppressWarnings("resource")
11         BufferedWriter bufferedWriter=new BufferedWriter(new 
12                 FileWriter("test"));
13         //int i=0;
14         long start=System.currentTimeMillis();
15         System.out.println("start:");
16         for ( int i=0;i<1e8;++i) {
17             Random r1=new Random();
18             //Random r2=new Random();
19             bufferedWriter.write(r1.nextInt(100)+"\t"+r1.nextInt(50)+"\n");
20         }
21         bufferedWriter.close();
22         long end=System.currentTimeMillis();
23         
24         System.out.println("second cost:"+(end-start)/1000);
25         
26     }
27     
28     public static void  main(String[] args) throws IOException {
29         writeBigFile();        
30     }
31     
32 
33 }

r1.next(100)表示生成[0,100)内的随机整数。所用时间:26s。

2)使用FileWrite写1亿条记录:

 1 package nioTest;
 2 import java.io.BufferedWriter;
 3 import java.io.FileWriter;
 4 import java.io.IOException;
 5 import java.util.Random;
 6 
 7 public class nio {
 8     public static void writeBigFile() throws IOException{
 9         
10         @SuppressWarnings("resource")
11         //BufferedWriter bufferedWriter=new BufferedWriter(new 
12             //    FileWriter("test"));
13         //int i=0;
14         FileWriter fileWriter=new FileWriter("test2");
15         long start=System.currentTimeMillis();
16         System.out.println("start:");
17         for ( int i=0;i<1e8;++i) {
18             Random r1=new Random();
19             //Random r2=new Random();
20             //bufferedWriter.write(r1.nextInt(100)+"\t"+r1.nextInt(50)+"\n");
21             fileWriter.write(r1.nextInt(100)+"\t"+r1.nextInt(50)+"\n");
22         }
23         //bufferedWriter.close();
24         fileWriter.close();
25         long end=System.currentTimeMillis();
26         
27         System.out.println("second cost:"+(end-start)/1000);
28         
29     }
30     
31     public static void  main(String[] args) throws IOException {
32         writeBigFile();        
33     }
34     
35 
36 }

所用时间为33秒,较BufferedWriter慢,BufferedWriter更适合大数据量的写入。

转载于:https://www.cnblogs.com/lz3018/p/4971475.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值