无法比较文件中的最后一个字

Unable to compare last word in the file

我一直在尝试将输入文件与数据库文件进行比较。该代码比较文件并输出输入文件 (test.txt) 中存在于数据库文件 (db.txt) 中的单词。但是但是我没有从输出中的输入文件中得到最后一句话。

test.txt 包含:

There is a book on the table

db.txt 包含:

book 
the 
table

因此我在输出中没有得到 table。

public static void main(String[] args) {
    try {
        File file = new File("G:\Project\test.txt");
        File file2 = new File("G:\Project\db.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
            stringBuffer.append("\n");
        }
        fileReader.close();
        StringTokenizer st = new StringTokenizer(stringBuffer.toString()," ");
        while (st.hasMoreTokens()) 
        {
            String word=st.nextToken();
            BufferedReader br = new BufferedReader(new FileReader(file2)); 
            String lin;

            while((lin=br.readLine())!=null){
                { if(word.equalsIgnoreCase(lin))
                    System.out.println(word);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

收到的输出:

book
the

我这里做错了什么?

您正在将换行符附加到 stringbuffer,这导致了这个问题。

从您的代码中删除以下行并尝试,它会起作用。

stringBuffer.append("\n");