2016-11-28 40 views
-1

我有一个具有类似这样的格式的文本文件读出部分线路:的BufferedReader - 从文本文件

===头1 ====

LINE-

LINE2

LINE3

===头2 ====

LINE1

LINE2

LINE3

我试图做的是分析这些出单独给一个字符串变量,所以当读取器检测"====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(); 
} 
+0

你得到了什么错误? –

+0

我无法看到标题的相关性。无论如何,您似乎都想打印出所有的行,因此无需关心该行是否为标题。 – Kayaman

+0

@Kayaman对不起,我忘了提及im试图将每个头和它的行分割成单独的字符串变量 – Matchbox2093

回答

1

您可以创建一个readLines()方法,将读取行,直到下一个报头和加载线到一个ArrayList,如在下面的代码行内评论称,从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; 
     }