2017-01-01 154 views
-6

我只想從文本文件中讀取一些特定的行而不是所有的行。 我嘗試下面的代碼:從文本文件中讀取行

public class BufferedReaderDemo { 

    public static void main(String[] args) throws IOException { 

     FileReader fr = new FileReader("Demo.txt"); 
     BufferedReader br = new BufferedReader(fr); 
     String line = br.readLine(); 

     while(line!=null) 
     { 
      System.out.println(line); 
      line = br.readLine(); 
     } 

     br.close(); 
    } 
} 

使用此代碼,我能得到的所有行。但我想在控制檯中打印一些特定的2-3行,以「命名空間」開頭並以「控制檯」結尾。

我該如何做到這一點?

+1

*「我該如何做到這一點?」*通過使用'if'語句。 – Andreas

+0

歡迎來到Stack Overflow。請閱讀http://stackoverflow.com/help/how-to-ask如果您顯示您正在閱讀的數據,這也可能有所幫助 – Mikkel

回答

0

使用String.startsWithString.endsWith

while(line!=null) 
{ 
    if(line.startsWith("namespace") && line.endsWith("Console")) { 
     System.out.println(line); 
    } 
    line = br.readLine(); 
} 
1

,如果你想知道如果一個行包含一些具體的話,你沒有選擇,你必須閱讀。

如果您只想打印這些行,可以在打印它們之前添加一個條件。

String line = br.readLine(); 

while(line!=null){ 
    if (line.startsWith("namespace") && line.endsWith("Console")){ 
     System.out.println(line); 
    } 
    line = br.readLine(); 
}