写文件 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 
 
备注:test1采用字符串连接的写入方式,一次写入一行,耗时最长;test2采用分别写入方式,耗时近1半;test3采用批量写入耗时不足一半。由此可知,test3的写入效率最高。
//两次测试结果
//已知 max=100000000
 
//test1耗时:46593/52906
//test2耗时:28563/28250
//test3耗时:21859/22594

你可能感兴趣的:(写文件 faster and faster)