簡體   English   中英

BufferedReader-計算包含字符串的行

[英]BufferedReader - count lines containing a string

我正在使用一個.txt文件,其中包含:“世界您好\\ 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”)時,它會打印2條包含“ o”的行,這是正確的,以及2條總行。 當我運行line.contains(“ world”)時,它打印0行,這是錯誤的,但總共提供2行。 但是我做錯了什么?

我用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

當其他人回答和評論時,我還認為您可能沒有閱讀您認為自己的文件...( 放松,這時不時發生在每個人身上)

但是,它也可能是文件的編碼器或您擁有的jdk的版本,也許您可​​以回答:

  1. 您用什么來創建文件?
  2. 您正在運行什么操作系統?
  3. 您正在使用什么JDK?

它可以澄清可能發生了什么

只是為了讓您知道,我運行了與使用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行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM