2016-11-28 57 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; 
     }