0

我需要扫描日志以查找多个关键字错误、操作系统、ARCH。以下代码适用于单个关键字搜索

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");
         }
     }
  }
4

3 回答 3

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;
    }
}
于 2013-08-29T00:52:18.410 回答
0

您可以使用正则表达式更优雅地表达它:

if (nextLine.matches(".*(ERROR|OS|ARCH).*")) {
    System.out.println("Failed" + " " + nextLine);
    ifError = true;
}
于 2013-08-29T01:09:59.123 回答
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");
         }
     }
  }
于 2013-08-29T00:56:43.947 回答