我需要扫描日志以查找多个关键字ERROR,OS,ARCH.Below代码与单个关键字搜索一起使用
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ErrorScanner
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner s = new Scanner(new File("Users/home/test.txt"));
boolean ifError = false;
while(s.hasNextLine())
{
String nextLine = s.nextLine();
if(nextLine.contains("ERROR"))
{
System.out.println("Failed" + " " + nextLine);
ifError = true;
}
}
if(! ifError)
{
System.out.println("Nothing found");
}
}
}
答案 0 :(得分:3)
试试这个:
if (nextLine.contains("ERROR")
|| nextLine.contains("OS")
|| nextLine.contains("ARCH")) {
// ...
}
或者更复杂的解决方案,如果有很多关键字且行很长,则非常有用:
// declared before the while loop
Set<String> keywords = new HashSet<String>(Arrays.asList("ERROR", "OS", "ARCH"));
// inside the while loop
for (String word : nextLine.split("\\s+")) {
if (keywords.contains(word)) {
System.out.println("Failed" + " " + nextLine);
ifError = true;
break;
}
}
答案 1 :(得分:0)
只需使用OR在代码中添加多个字符串包含检查。你走了:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ErrorScanner
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner s = new Scanner(new File("Users/home/test.txt"));
boolean ifError = false;
while(s.hasNextLine())
{
String nextLine = s.nextLine();
if(nextLine.contains("ERROR") || nextLine.contains("OS") || nextLine.contains("ARCH"))
{
System.out.println("Failed" + " " + nextLine);
ifError = true;
}
}
if(! ifError)
{
System.out.println("Nothing found");
}
}
}
答案 2 :(得分:0)
您可以使用正则表达式更优雅地表达它:
if (nextLine.matches(".*(ERROR|OS|ARCH).*")) {
System.out.println("Failed" + " " + nextLine);
ifError = true;
}