按行读取文件比较Scanner和RandomAccessFile读取的效率
来源:互联网 发布:jira 数据库结构 编辑:程序博客网 时间:2024/05/20 05:46
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.848BufferedInputStream + DataInputStreamBufferedOutputStream + DataOutputStream2.935
我们可以看到两者差距约32倍,RandomAccessFile也太慢了。由其源码可见,RandomAccessFile每读/写一个字节就需对磁盘进行一次I/O操作。
- 按行读取文件比较Scanner和RandomAccessFile读取的效率
- Scanner和BufferedReader读取文件速度比较
- 关于C 和 python读取文件的效率比较
- RandomAccessFile随机访问文件的读取和写入
- FileInputStream RandomAccessFile BufferedReader MappedByteBuffer 大文件数据读取效率测试
- java 读取文件 RandomAccessFile
- RandomAccessFile读取文件
- Scanner读取文件输入
- java文件读取Scanner
- 随机读取文件--RandomAccessFile的应用实例
- scanner按指定的分割符号读取文件
- Scanner读取文件时的错误
- Java按行读取正在被动态写入的大文件实例--使用RandomAccessFile(1)
- 随机文件读取流RandomAccessFile
- Java RandomAccessFile随机读取文件
- RandomAccessFile && MappedByteBuffer读取大文件
- RandomAccessFile 读取
- 在文件指定位置读取和写入内容RandomAccessFile
- abstract class 和 interface 的区别
- POJ 2653 Pick-up sticks
- GD sWidgets使用
- Bootstrap && Jetstrap
- ZOJ Problem Set - 3664 Split the Rectangle
- 按行读取文件比较Scanner和RandomAccessFile读取的效率
- sqlplus执行创建表sql
- 6.黑马程序员-函数
- 【mysql】mysql重建索引命令、查询数据表索引、创建索引、删除索引
- Headway 主题的安装
- 浅谈android的selector背景选择器
- uva 141 The Spot Game
- ios 抖动动画效果
- 22_输出单个字符