2012-11-21 26 views
0

我需要獲取實際上以類似45- 的東西.log開頭的文件的名稱。我可以搶45,但不是其他的,因爲東西由隨機數組成。此外,這樣的文件已經在服務器上,我需要事先查找它。使用jsp解析文本文件的名稱

我已經嘗試過類似如下:

 <% 
     String line =""; 

     String file = "/tmp/smsrouter/" + pageContext.getAttribute("cid"); 
     BufferedReader br = new BufferedReader(new FileReader(file)); 
     int count = 0; 
     int lineNumber = 0; 
     while((line=br.readLine())!=null) 
     { 
      String[] parts = line.split("\\,"); 

      lineNumber++; 
      if(parts[3].equals("0") && count < lineNumber) 
      { 
        count++; 
      } 
     } 
     count = (count/lineNumber)*100; 
     br.close(); 

     %> 

顯然,它不會得到任何結果符合市場預期。那我該怎麼辦?

+1

你想完成什麼?您需要獲取的名稱以文本形式存在於文件中,或者是您使用'pageContext.getAttribute(「cid」)'獲取的內容。順便說一句,你應該只使用jsp的顯示數據(視圖)。把你的邏輯放在一個Servlet中分離問題更好。 –

+0

@SérgioMichels:由於數據庫查詢,cid已經在文件中。所以問題在於,我在某些目錄(所謂的/ tmp/smsrouter)上有很多文件。因此,我想根據前綴cid-something.log來搜索相應的文件,然後我會用各自的文件來完成其餘的工作。 –

+0

你有多個文件具有相同的cid?你可以使用[contains](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence))嗎? –

回答

1

爲什麼不選擇iterator/tmp/smsrouter/dir並匹配你想要的文件名?

File[] files = new File("/tmp/smsrouter/").listFiles(); 

    for (File file : files) { 
     if (file.isDirectory()||!file.getName().startsWith("45-")) { 
      continue; 
     } else { 
      BufferedReader br = new BufferedReader(new FileReader(file)); 
      int count = 0; 
      int lineNumber = 0; 
      while((line=br.readLine())!=null) 
      { 
       String[] parts = line.split("\\,"); 

       lineNumber++; 
       if(parts[3].equals("0") && count < lineNumber) 
       { 
        count++; 
       } 
      } 
      count = (count/lineNumber)*100; 
      br.close(); 
     } 
    } 

可能你想提取計數邏輯到另一個方法。希望這個幫助。

這不是在真實生產系統中建議的,因爲調用可能很長,以致可能引發請求超時。

+0

謝謝,我真的很感激。 –