写大文件

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更适合大数据量的写入。

posted @ 2015-11-17 13:43  lz3018  阅读(248)  评论(0编辑  收藏  举报