2016-11-28 8 views
-1

からセクション内の行を読み取る:BufferedReaderの - 私はこのような形式を持つテキストファイル持つテキストファイル

を===ヘッダ1 ====

LINE1

LINE2

LINE3

===ヘッダ2 ====

LINE1

私が何をしようとしているLINE2

LINE3

は、読者が"====Header1===="を検出したときに、それはまたそれが"===Header2==="を検出したゴマの下にすべての行を読み込みます、String型の変数に個別にこれらを解析であります変数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申し訳ありませんが、各ヘッダーとその行を個々の文字列変数に分割しようとしています。 – Matchbox2093

答えて

1

あなたは次のヘッダまでのラインを読み、ArrayListにラインをロードし、インラインコメントを次のコードに示すようmain()からreadLines()を呼び出します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; 
     } 
関連する問題