java基础之读写性能

PS:来源忘记,尚未查到,希望见过该代码出现的原址能慷慨告知,先谢谢啦~

apacheAPI,scanner和jdkAPI读取文件的内存以及时间的对比

public class JavaProperty {

	/**
	 * 创建一个文件
	 * 写入数据,作为测试文本
	 */
	public void MakeFile() {
		try {
			File file = new File("D:\\phone.txt");
			if (file.exists()) {
				file.delete();
			}
			file = new File("D:\\phone.txt");
			OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

			for (int i = 0; i < 2*1000*1000; i++) {
				bw.write(bulidPhone());
				bw.newLine();
			}
			bw.close();//我错了
			os.close();		
			System.out.println("file create succ");
		}catch(Exception e) {
			System.out.println("io error");
		}
	}
	/**
	 * 随机产生一个long数字
	 * @return 字符串格式返回
	 */
	public String bulidPhone() {
		Long long1 = new Random().nextLong();
		return String.valueOf(long1);
	}

	/**
	 * 测试
	 * apacheAPI
	 * 读写性能
	 */
	public void apacheAPITest() {
		try {
			long start = System.currentTimeMillis();
			File file = new File("D:\\phone.txt");		
			BufferedReader br = new BufferedReader(new FileReader(file));

			while (br.ready()) {
				br.readLine();
			}
			long end = System.currentTimeMillis();

			System.out.println("apacheAPI内存使用:"+(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
			System.out.println("apacheAPI时间使用:"+(end - start));

		}catch(Exception e) {
			System.out.println("apacheAPI");
		}
	}

	/**
	 * 测试
	 * scannerTest
	 * 读写性能
	 */
	public void scannerTest() {
		try {
			long start = System.currentTimeMillis();
			File file = new File("D:\\phone.txt");
			InputStream is = new FileInputStream(file);
			Scanner scanner = new Scanner(is , "UTF-8");

			while (scanner.hasNextLine()) {
				scanner.nextLine();
			}
			long end = System.currentTimeMillis();

			System.out.println("scannerTest内存使用:"+(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
			System.out.println("scannerTest时间使用:"+(end - start));

		}catch(Exception e) {
			System.out.println("scannerTest");
		}

	}

	/**
	 * 测试
	 * jdkAPITest
	 * 读写性能
	 */
	public void jdkAPITest() {
		try {
			long start = System.currentTimeMillis();
			File file = new File("D:\\phone.txt");		
			LineIterator li = FileUtils.lineIterator(file);

			while (li.hasNext()) {
				li.nextLine();
			}
			long end = System.currentTimeMillis();

			System.out.println("jdkAPITest内存使用:"+(Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));
			System.out.println("jdkAPITest时间使用:"+(end - start));

		}catch(Exception e) {
			System.out.println("jdkAPITest");
		}

	}


	public static void main(String[] args) {
			JavaProperty jp = new JavaProperty();
			jp.MakeFile();
			jp.apacheAPITest();
			jp.scannerTest();
			jp.jdkAPITest();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值