ファイルを書く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
"); } 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
");// 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
"); //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(); } } }

備考:test 1は文字列接続の書き込み方式を採用し、一度に1行書き込み、最も時間がかかる.test 2はそれぞれ書き込む方式を採用し、1半近くかかる.test 3は一括書き込みを採用するのに半分未満の時間がかかります.このことからtest 3の書き込み効率が最も高いことが分かる.

// 
//  max=100000000
 
//test1 :46593/52906
//test2 :28563/28250
//test3 :21859/22594