BufferedReader - 包含字符串的计数行

时间:2014-07-10 17:31:01

标签: java bufferedreader

我使用的是一个.txt文件,其中包含:“Hello world \ n你好今天怎么样?”我想计算一行是否包含字符串,以及总行数。我用:

File file = new File(file_Path);
try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;
    int i=0;
    int j=0;
    while ((line = br.readLine()) != null) {
        j++;
        if (line.contains("o")) { //<----------
            i++;
        }
    }
System.out.print("Lines containing the string: " + i + " of total lines " + j-1);

当我运行并测试line.contains(“o”)时,它打印出包含“o”的2行,这是正确的以及总共2行。当我运行line.contains(“world”)时,它打印0行,这是错误的,但总共给出2行。但是我做错了什么?

2 个答案:

答案 0 :(得分:1)

我用StringReader

测试了它
String str = "Hello world\nHow are you doing this day?";
StringReader sr = new StringReader(str);
try {
  BufferedReader br = new BufferedReader(sr);
  String line;
  int i = 0;
  int j = 0;
  while ((line = br.readLine()) != null) {
    j++;
    if (line.contains("world")) { // <----------
      i++;
    }
  }
  System.out
      .println("Lines containing the string: " + i
          + " of total lines " + j);
} catch (Exception e) {
  e.printStackTrace();
}

你的文件内容不一定是你的想法,因为我得到了

Lines containing the string: 1 of total lines 2

答案 1 :(得分:0)

正如其他人的回答和评论一样,我也认为你可能没有阅读你认为自己的文件......(放松它会不时发生在每个人身上

但是,它也可能是文件的编码器或你拥有的jdk的版本,也许你可以回答:

  1. 您用什么来创建文件?
  2. 您正在运行什么操作系统 这个?
  3. 您使用的是什么JDK?
  4. 它可以澄清可能发生的事情

    只是为了让您知道,我使用jdk8运行了相同的代码并且对我工作正常。

    如下我所做的测试:

    1)我将您的代码放在一个函数中:

    int countLines(String filename, String wording) {
        File file = new File(filename);
        String line;
        int rowsWithWord = 0;
        int totalRows = 0;
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            while ((line = br.readLine()) != null) {
                totalRows++;
                if (line.contains(wording)) {
                    rowsWithWord++;
                }
            }
        } catch (IOException e) {
            System.out.println("Error Counting: " + e.getMessage());
        }
        System.out.println(String.format("Found %s rows in %s total rows", rowsWithWord, totalRows));
        return rowsWithWord;
    }
    

    2)并运行以下单元测试

    @Test
    public void testFile() {
    
        try (FileWriter fileWriter = new FileWriter(new File("C:\\TEMP\\DELETE\\Hello.txt"));
             BufferedWriter writer = new BufferedWriter(fileWriter)) {
            writer.write("Hello world\nHow are you doing this day?");
        } catch (IOException e) {
            System.out.println("Error writing... " + e);
        }
    
        int countO = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "o");
        Assert.assertEquals("It did not find 2 lines with the letters = o", 2, countO);
        int countWorld = fileUtils.countLines("C:\\TEMP\\DELETE\\Hello.txt", "world");
        Assert.assertEquals("It did not find 1 line with the word = world", 1, countWorld);
    
    }
    

    我得到了预期的结果:

      

    在总共2行中找到2行

         

    在总共2行中找到1行