bufferedReader - 从文本文件中读取部分行

bufferedReader - reading out lines in sections from a text file

我有一个格式与此类似的文本文件:

===标题 1====

LINE1

LINE2

LINE3

===标题 2====

LINE1

LINE2

LINE3

我想做的是将它们分别解析为字符串变量,因此当 reader 检测到 "====Header1====" 时,它还会读取下面的所有行,直到检测到 [=12] =], 这将是变量 Header1 等等

我目前在读出这些行直到它检测到下一个 header 时遇到问题。我想知道任何人都可以对此有所了解吗?这是我目前所拥有的

try (BufferedReader br = new BufferedReader(new FileReader(FILE))) {
    String sCurrentLine;
    while ((sCurrentLine = br.readLine()) != null) {
        if (sCurrentLine.startsWith("============= Header 1 ===================")) {
            System.out.println(sCurrentLine);
        }
        if (sCurrentLine.startsWith("============= Header 2 ===================")) {
            System.out.println(sCurrentLine);
        }
        if (sCurrentLine.startsWith("============= Header 3 ===================")) {
            System.out.println(sCurrentLine);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

您可以创建一个 readLines() 方法,该方法将读取行直到下一个 header 并将行加载到数组列表,从 main() 调用 readLines() ,如图所示在下面的带有内联注释的代码中:

 public static void main(String[] args) {

     BufferedReader br = null;
      try {
           br = new BufferedReader(new FileReader(new File(FILE)));

           //read the 2rd part of the file till Header2 line
           List<String> lines1 = readLines(br, 
                              "============= Header 2 ===================");

           //read the 2rd part of the file till Header3 line
           List<String> lines2 = readLines(br, 
                              "============= Header 3 ===================");

            //read the 3rd part of the file till end        
            List<String> lines3 = readLines(br, "");

        } catch (IOException e) {
             e.printStackTrace();
        } finally {
            //close BufferedReader
        }
   }

   private static List<String> readLines(BufferedReader br, String nextHeader) 
                                                  throws IOException {
                 String sCurrentLine;
                 List<String> lines = new ArrayList<>();
                 while ((sCurrentLine = br.readLine()) != null) {
                     if("".equals(nextHeader) || 
                         (nextHeader != null &&      
                       nextHeader.equals(sCurrentLine))) {
                         lines.add(sCurrentLine);
                     }
                 }
                 return lines;
      }