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();
	}
}

 

你可能感兴趣的:(java基础之读写性能)