搜索令牌的文本文件并返回匹配Java

时间:2014-04-24 23:30:58

标签: java arraylist text-files search-engine

我试图在某种程度上建立一个搜索引擎,用户在.txt文件中提供的密钥不超过5个,然后返回文件中与给定的每个密钥匹配的行。我已经将用户的密钥串分成了令牌以与之比较,现在我已将txt文件中的每一行存储到字符串的arraylist中。当我尝试将文件中的每一行与令牌进行比较时,找不到任何内容,我知道它至少应该匹配一个。

我相信我没有得到匹配,因为arraylist元素是字符串,而contains()方法试图将整行与一个标记匹配。

我如何将arraylist中的字符串分成标记,以便我可以匹配arraylist中的单个单词? 或者我应该采用不同的方式来解决这个问题?

Scanner input = new Scanner(System.in);
    ArrayList<String> fileList = new ArrayList<>();


    String userInput; //declare a string variable to store the user search input    
    System.out.println("Enter up to 5 words you would like to search for along with the"
            + " file to be searched at the end:");
    userInput = input.nextLine(); //store the input in the String variable


    String[] searchString = userInput.split("\\s"); //split up the string into tokens with 
                //spaces as delimiters
    String fileName = searchString[searchString.length-1]; //get the name of the file and
                //store it in a string variable

    Scanner scan = new Scanner(new File(fileName)); //scanner object that locates the file
    scan.useDelimiter("\\n");

    while(scan.hasNextLine()) {
        fileList.add(scan.nextLine());

    } // while loop that adds the contents so the arraylist

    for(int i = 0; i < fileList.size(); i++) {
        System.out.println(i);
        for(int j = 0; j < searchString.length; j++) {
            int match = 0;
            System.out.println(j);
            if(fileList.contains(searchString[j])) {
                match++;
                System.out.println("match" + match);
                if(match >= searchString.length-1) {
                    System.out.println(fileList.get(i));
                }
                else {
                    System.out.println("No matches found.");
                }
            }

        }

    }

0 个答案:

没有答案