[英]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.