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