2014-07-25 21 views
1

这应该是直接的,但由于某些原因,当我将文件下载到SD卡后尝试对文件中的字数进行计数时,该数字似乎是关闭的。此外,出现的次数越多,我的结果似乎就越少。我使用Microsoft Word来验证出现次数(仅使用忽略大小写和整个单词)。为了测试出现次数,我使用下面的“the_counter”变量。我也确认下载&这个完整的文件被下载到我的SD卡上没有任何问题。这让我疯狂 - 我在想Word不会在这里出错,所以下面的代码可能有什么问题?Android:计算SD卡上文件的字数

它可能是空白或文件中的特殊字符导致问题 - 有没有办法清理文件来验证这一点?

//Find the directory for the SD Card using the API 
     File sdcard = Environment.getExternalStorageDirectory(); 

     //Get the text file 
     File file = new File(sdcard,TEMP_FILE); 

     //Read text from file 
     //StringBuilder text = new StringBuilder(); 
     m_tree = new Tree(); 
     int i=0; 
     BufferedReader br = null; 
     long the_counter=0; 
     try { 
      br = new BufferedReader(new FileReader(file)); 
      String line; 
      String []arLine; 
      while ((line = br.readLine()) != null) { 
       //get each word in line 
       if(line.length()==0) 
        continue; 
       arLine = line.split("\\s+"); 

       //now add each word to search tree 
       for(i=0;i< arLine.length;++i){ 
        m_tree.insert(arLine[i]); 
        if(arLine[i].equalsIgnoreCase("a")) 
         ++the_counter; 
       } 
      } 
      m_sTest = Long.toString(the_counter) ; 
      br.close(); 

我编辑了我的代码,以读取每行每个字符并手动创建单词。我仍然得到相同的结果。

br = new BufferedReader(new FileReader(file)); 
      String line; 
      String []arLine; 
      StringBuilder word = new StringBuilder(); 
      while ((line = br.readLine()) != null) { 
       //check for word at end of last line 
       if(word.length()>0){ 
        m_tree.insert(word.toString()); 
        word.setLength(0); 
       } 
       char[] lineChars = new char [line.length()]; 
       line.getChars(0,line.length(),lineChars,0); 

       for(char c: lineChars){ 
        if(c== ' '){ 
         //if we have a word then store and clear then move on 
         if(word.length()>0){ 
          m_tree.insert(word.toString()); 
          word.setLength(0); 
         } 
        } 
        else{ 
         word.append(c); 
        } 
       } 
+0

任何人都有任何线索? – Mike6679

+0

您想要读取的文件格式是什么?如果它是一个Microsoft Word文件,请尝试用纯文本文件测试您的应用程序。 –

+0

这是一个纯文本文件 – Mike6679

回答

0

这是问题是,我无法用言语间占特殊字符:即: 这-是个字,而不是一个。我甚至不确定这是合适的语法或写作,但它在这个文件中,它肯定会抛弃我的计数。