Java读取文本文件并搜索一行

时间:2014-02-04 04:19:20

标签: java file

我有以下代码,它通过文件读取并搜索以subject开头并打印出该行的行。但我只想阅读包含'主题'的第一行,但目前它获得了以'主题'开头的所有行,我如何配置以便搜索第一个'主题'并打印那一行?

            br = new BufferedReader(new FileReader("FilePath"));
            StringBuilder sb = new StringBuilder();
            String line = "";

            while ((line = br.readLine()) != null) {

                if (line.startsWith("Subject ")) {
                    System.out.println(line);

                }
            }

4 个答案:

答案 0 :(得分:2)

使用休息;语句,

br = new BufferedReader(new FileReader("FilePath"));
            StringBuilder sb = new StringBuilder();
            String line = "";

            while ((line = br.readLine()) != null) {

                if (line.startsWith("Subject ")) {
                    System.out.println(line);
                    break;
                }
            }

答案 1 :(得分:0)

您应该尝试使用正则表达式来查找所需的所有匹配项 Pattern,例如"Subject*\n"。 看看这个关于Regex的非常好的教程:www.vogella.com/tutorials/JavaRegularExpressions/article.html

答案 2 :(得分:0)

你没有停止你的循环,所以它将获取到最后一行;

试试这个

 if (line.startsWith("Subject ")) {
   System.out.println(line);
   break; // break the lop on success match
 }

答案 3 :(得分:0)

使用ArrayList,您可以使用" Subject"保存每一行。并且可以遍历所有这些,您可以根据您的要求使用它

    ArrayList<String> list = new ArrayList<String>(); 
    br = new BufferedReader(new FileReader("FilePath"));
    StringBuilder sb = new StringBuilder();
    String line = "";

    while ((line = br.readLine()) != null) {

        if (line.startsWith("Subject ")) {
            list.add(line);

        }
    }
    System.out.println(list.get(0);
相关问题