按行读取文件比较Scanner和RandomAccessFile读取的效率

本文对比了使用RandomAccessFile和Scanner两种方式读取文件的效率,并通过实验数据说明了使用Scanner进行文件读取的优越性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	public void importLineData(String dbid, File f, double ddd){
		if(f.exists() && f.isFile() && f.length()>0){
			try {
				RandomAccessFile raf = new RandomAccessFile(f,"r");
					int count = 0;
					while (raf.getFilePointer() < raf.length()) {
						String temp = raf.readLine();
						String d = new String(temp.getBytes("ISO-8859-1"),"UTF-8");
						while(!d.endsWith(");")){
							temp = raf.readLine();
							d += new String(temp.getBytes("ISO-8859-1"),"UTF-8");
						}
						String sql = d.substring(0, d.length()-1);
						count++;
					}
				raf.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public void importLineData(String dbid, File f, int startLine){
		if(f.exists() && f.isFile() && f.length()>0){
			try {
				Scanner sc = new Scanner(f);
					int count = 0;
					while(sc.hasNextLine()){
						String temp = sc.nextLine();
						String d = new String(temp.getBytes("ISO-8859-1"),"UTF-8");
						while(!d.endsWith(");")){
							temp = sc.nextLine();
							d += new String(temp.getBytes("ISO-8859-1"),"UTF-8");
						}
						String sql = d.substring(0, d.length()-1);
						count++;
					}
				sc.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

 

以上两个方法去读取同一个文件,使用Scanner按行读取文件效率高好多好多倍,内存占用高一点点而已;而使用RandomAccessFile按行读取数据效率极低,推荐使用Scanner。

RandomAccessFile类。其I/O性能较之其它常用开发语言的同类性能差距甚远,严重影响程序的运行效率。

在改进之前先做一个基本测试:逐字节COPY一个12兆的文件(这里牵涉到读和写)。

耗用时间(秒)
RandomAccessFileRandomAccessFile95.848
BufferedInputStream + DataInputStreamBufferedOutputStream + DataOutputStream2.935

我们可以看到两者差距约32倍,RandomAccessFile也太慢了。由其源码可见,RandomAccessFile每读/写一个字节就需对磁盘进行一次I/O操作。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值