[英]Search for specific string inside text file
我目前正在開發一個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");
}
}
}
}
}
我認為您的程序可以成功在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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.