分享

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

 tracyf 2015-06-11
  1. public void importLineData(String dbid, File f, double ddd){  
  2.     if(f.exists() && f.isFile() && f.length()>0){  
  3.         try {  
  4.             RandomAccessFile raf = new RandomAccessFile(f,"r");  
  5.                 int count = 0;  
  6.                 while (raf.getFilePointer() < raf.length()) {  
  7.                     String temp = raf.readLine();  
  8.                     String d = new String(temp.getBytes("ISO-8859-1"),"UTF-8");  
  9.                     while(!d.endsWith(");")){  
  10.                         temp = raf.readLine();  
  11.                         d += new String(temp.getBytes("ISO-8859-1"),"UTF-8");  
  12.                     }  
  13.                     String sql = d.substring(0, d.length()-1);  
  14.                     count++;  
  15.                 }  
  16.             raf.close();  
  17.         } catch (FileNotFoundException e) {  
  18.             e.printStackTrace();  
  19.         } catch (IOException e) {  
  20.             e.printStackTrace();  
  21.         }  
  22.     }  
  23. }  
  24.   
  25.   
  26. public void importLineData(String dbid, File f, int startLine){  
  27.     if(f.exists() && f.isFile() && f.length()>0){  
  28.         try {  
  29.             Scanner sc = new Scanner(f);  
  30.                 int count = 0;  
  31.                 while(sc.hasNextLine()){  
  32.                     String temp = sc.nextLine();  
  33.                     String d = new String(temp.getBytes("ISO-8859-1"),"UTF-8");  
  34.                     while(!d.endsWith(");")){  
  35.                         temp = sc.nextLine();  
  36.                         d += new String(temp.getBytes("ISO-8859-1"),"UTF-8");  
  37.                     }  
  38.                     String sql = d.substring(0, d.length()-1);  
  39.                     count++;  
  40.                 }  
  41.             sc.close();  
  42.         } catch (FileNotFoundException e) {  
  43.             e.printStackTrace();  
  44.         } catch (IOException e) {  
  45.             e.printStackTrace();  
  46.         }  
  47.     }  
  48. }  

 

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

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

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

耗用时间(秒)
RandomAccessFile RandomAccessFile 95.848
BufferedInputStream + DataInputStream BufferedOutputStream + DataOutputStream 2.935

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多