按行读取文件比较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操作。

原创粉丝点击