当前位置: 首页 > 知识库问答 >
问题:

我的文件中有N行,我需要找到一行,然后打印第三行?

宋明亮
2023-03-14

在下面的代码中,我将打印给定字符串的下一行,而不是第三行。谁能给我一个主意吗?蒂娅。

 while ((s = br.readLine()) != null) {
     String[] arr = s.split("\\r?\\n");

     for (int i = 0; i < arr.length; i++) {
         if (s.contains(keyword)) {
             String nextLine = br.readLine();
             System.out.println(s);
             System.out.println(nextLine);
         }
     }
}

共有1个答案

东郭勇
2023-03-14

在计数器变量的帮助下,您可以再次使用while循环来读取另外3行(如果可用),例如:

String desiredLine = "";
int linesFromFoundKeyword = 3;
String keyword = "runnable";
String textFile = ""; // *** Text File Path Here ***
boolean found = false;
    
try (BufferedReader br = new BufferedReader(new FileReader(textFile))) {
    String s;
    while ((s = br.readLine()) != null) {
        String[] arr = s.split("\\s+");
            
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].contains(keyword)) {
                found = true;
                int counter = 0;
                while ((s = br.readLine()) != null) {
                    counter++;
                    if (counter == linesFromFoundKeyword) {
                        desiredLine = s;
                         break;
                    }
                }
                if (!desiredLine.isEmpty()) {
                    break;
                } 
            }
        }
        if (found) {
            break;
        }
    }
}
catch (FileNotFoundException ex) {
    ex.printStackTrace();
}
catch (IOException ex) {
    ex.printStackTrace();
}
    
if (!found) {
    System.out.println("Could not locate the Keyword (" + keyword 
                     + ") in file!");
}
else if (found && desiredLine.isEmpty()) {
    System.out.println("Keyword (" + keyword + ") was found but the "
                     + "desired data line was not achievable!");
}
else {
    System.out.println("The desired Data Line is for the keyword: '" 
                     + keyword + "' is:");
    System.out.println(desiredLine);
}
 类似资料: