【问题标题】:.contains() not working with BufferedReader.contains() 不适用于 BufferedReader
【发布时间】:2020-08-17 22:02:01
【问题描述】:

我正在尝试创建一个程序来检查文件并将行打印回给我,如果它们包含单词“TRUE”

这是文件内容

TRUE,TRUE
FALSE,TRUE
FALSE,FALSE
TRUE,FALSE
TRUE,TRUE
TRUE,FALSE

这是程序

public static void main(String[] args) {
    // TODO Auto-generated method stub
    
    BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader(
                "C:\\Users\\tree3\\Desktop\\Programming\\file.txt"));
        String line = reader.readLine();
        while (line != null) {
            
            if(line.contains("TRUE")) { 
                System.out.println(line);
                // read next line
                line = reader.readLine();
            } else {
                System.out.println("false");
            }
            
            
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
}

程序只是无限期地打印false

这是为什么?

【问题讨论】:

  • 请注意,如果一行不包含单词TRUE,则您不会阅读下一行。您应该将以下语句移动到 while 循环的末尾:line = reader.readLine();

标签: java file while-loop bufferedreader


【解决方案1】:
public static void main(String[] args) {
    try (BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\tree3\\Desktop\\Programming\\file.txt"))) {
        String line = reader.readLine();
        while (line != null) {
            if (line.contains("TRUE")) {
                System.out.println(line);
            } else {
                System.out.println("false");
            }
            // read next line
            line = reader.readLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

不要在 if 语句旁边阅读下一行。如果 if 语句不正确怎么办?你永远不会继续前进并无限期地卡在这条线上。

使用 try-with-resources (Java 7+),不用担心关闭资源。


清理器(Java 8+):

try (BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\tree3\\Desktop\\Programming\\file.txt"))) {
    reader.lines().forEach(line -> System.out.println(line.contains("TRUE")));
} catch (IOException e) {
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2017-04-04
    • 1970-01-01
    • 2019-04-11
    相关资源
    最近更新 更多