2014-01-08 136 views
0

我目前正在開發一個Java應用程序,它將從特定文件夾中讀取文本文件的內容。該應用程序已經能夠讀取文本文件的內容,但是,文本文件是服務器日誌,我只需要從它們的內容中獲取數據,如錯誤名稱,時間,日期等。關於如何做到這一點的任何想法,或可以幫助我的功能?搜索文本文件中的特定字符串

爲了更好地看待這裏是我的代碼。

public class ListFiles { 

    public static void main(String[] args) throws FileNotFoundException, 
      IOException { 

     // Directory path here 
     String path = "C:/Users/Pasusani/Desktop/logs"; 

     String files; 
     File folder = new File(path); 
     File[] listOfFiles = folder.listFiles(); 

     for (int i = 0; i < listOfFiles.length; i++) { 

      if (listOfFiles[i].isFile()) { 
       files = listOfFiles[i].getName(); 
       if (files.endsWith(".txt") || files.endsWith(".TXT")) { 
        if (listOfFiles[i].getName().equals("R320-txtfile.txt")) { 
         JOptionPane.showMessageDialog(null, listOfFiles[i] 
           .getName().toString()); 

         String paths = "C:/Users/Pasusani/Desktop/logs/" 
           + listOfFiles[i].getName().toString(); 
         FileReader file = new FileReader(paths); 
         BufferedReader reader = new BufferedReader(file); 

         String text = ""; 
         String line = reader.readLine(); 
         while (line != null) { 
          text += line; 
          line = reader.readLine(); 
         } 
         System.out.println(text); 
         JTextArea ta = new JTextArea(); 
         ta.setVisible(true); 
         ta.setText(text); 

        } else if (listOfFiles[i].getName().equals("try.txt")) { 
         String paths = "C:/Users/Pasusani/Desktop/logs/" 
           + listOfFiles[i].getName().toString(); 
         FileReader file = new FileReader(paths); 
         BufferedReader reader = new BufferedReader(file); 

         String text = ""; 
         String line = reader.readLine(); 
         while (line != null) { 
          text += line; 
          line = reader.readLine(); 
         } 
         System.out.println(text); 
         JTextArea ta = new JTextArea(); 
         ta.setVisible(true); 
         ta.setText(text); 

        } 

        else { 
         JOptionPane.showMessageDialog(null, "hah"); 
        } 

        // System.out.println(files); 
       } else { 
        JOptionPane.showMessageDialog(null, "wala lang"); 
       } 
      } 
     } 
    } 

} 
+0

的['Scanner'](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)類有一些方法可能是這裏得心應手。 –

+0

不知道有問題的日誌文件的確切佈局,以及什麼「等」你試圖提取,這是很難提出具體的建議。 – keshlam

+0

不要在意代碼,請向我們展示示例輸入(日誌文件行)和所需輸出 – Bohemian

回答

0

我想你的程序可以在JTextArea中成功輸出日誌吧?

您需要根據日誌文件的結構添加語句來處理從Bufferreader獲取的文本。沒有您的日誌文件的知識,我們無法幫助您。

您可能需要使用String的contains(String str),substring(int beginIndex,int endIndex)和indexOf(String str)。一個簡單的示例:

public static String testMethod(){ 

    String a = "hello error"; 
    if(a.contains("error")) 
     return a.substring(a.indexOf("error"), a.indexOf("error")+5); 
    else 
     return "not found"; 
} 
相關問題