如何检查文本文件中是否存在单词

时间:2019-10-26 03:57:16

标签: java

我是Java新手,正在编写代码来检查日志文件中是否存在ID。如果该ID存在于日志文件中,则应打印该ID已存在。但是,如果它不存在,那么它应该执行一些任务。

我有一个字符串p1 = 1234

,想要检查该字符串是否存在于日志文件中。

p1 = 1234;
Scanner scanner=new Scanner("sample.log");
While(scanner.hasNextLine()){
if(p1.equals(scanner.nextLine().trim())){
 system.out.println("ID already exist")}
else{system.out.println("ID not present ")}

我的sample.log文件中包含一些文本,例如:

2019年10月21日,[WARN],2324

2019年10月21日,[WARN],1234

2019年10月21日,[INFO],3343等。

3 个答案:

答案 0 :(得分:1)

“ Sample.log”应作为新文件(“ sample.log”)给出,如下面的代码所述

String p1 = "1234";
Scanner scanner=new Scanner(new File(pathToFile));
while(scanner.hasNext()){
    String aString = scanner.nextLine();
    System.out.println(aString);
    if(aString.indexOf(p1) > 0){
        System.out.println("ID already exist");
    }
    else
    {
        System.out.println("ID not present ");
    }
}

答案 1 :(得分:1)

这是您的1班轮:

if (new Scanner(new File(pathToFile)).useDelimiter("\\Z").next().contains(p1)) {
     System.out.println("ID already exist");
} else {
    System.out.println("ID not present ");
}

此处的“技巧”使用的是"\\Z"(正则表达式表示整个输入的结尾),因此next()会读取整个文件。

答案 2 :(得分:0)

您可以使用BufferedReader。例如:

// Source file: IDCheck.java

import java.io.BufferedReader;
import java.io.FileReader;


public class IDCheck{

    // This method checks if ID exists in log file
    public static boolean hasID(String logFile, String id){ 
        try{
            BufferedReader buff=new BufferedReader(new FileReader(logFile));
            String s;
            while((s=buff.readLine())!=null){ 
                if(s.trim().contains(id)){
                    return true;
                }               
            }
            buff.close();
        }catch(Exception e){e.printStackTrace();}
    return false;
    }



    //Main:
    public static void main(String[] arg){

        //Now test:
        if(IDCheck.hasID("Sample.log","1234")){
            System.out.println("ID already exists");
        }else{
            System.out.println("ID not present");
        }       
    }
}