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

时间:2016-11-28 20:48:34

标签: java bufferedreader

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

===头1 ====

LINE1

LINE2

LINE3

===头2 ====

LINE1

LINE2

LINE3

我想要做的是将这些分别解析为String变量,所以当读者检测到"====Header1===="时,它还会读取下面的所有行,直到它检测到"===Header2===",这将是变量Header1等等

我现在有问题,读出线路直到它检测到下一个标题。我想知道是否有人可以对此有所了解?这是我到目前为止所拥有的

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();
}

1 个答案:

答案 0 :(得分:1)

您可以创建一个readLines()方法,该方法将读取直到下一个标题的行并将这些行加载到一个arraylist,从readLines()调用main(),如下面的代码所示,带内联注释:

 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;
      }