从文本文件中读取行 [英] Read lines from Text file
本文介绍了从文本文件中读取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了下面的代码:
pre $ c $ public元素BufferedReaderDemo {
public static void main (String [] args)抛出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();
$ b $ p
$ b
使用这段代码,我可以得到所有的行。但是我想在控制台打印一些特定的2-3行,以命名空间开始,以控制台结束。
我怎样才能做到这一点?
解决方案
你没有选择,如果你想知道一行是否包含某些特定的单词,你必须阅读它。
如果您只想打印这些行,可以在打印之前添加一个条件。
String line = br.readLine();
$ b $ while(line!= null){
if(line.startsWith(namespace)&& line.endsWith(Console)){
System。通过out.println(线);
}
line = br.readLine();
}
I just want to read some specific lines from a text file not all the lines. I tried the following code:
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();
}
}
Using this code I am able to get all the lines. But I want to print some specific 2–3 lines in console that start with "namespace" and end with "Console".
How can I achieve this?
解决方案
You have no choice, if you want to know if a line contains some specific words, you have to read it.
If you want only print these lines, you can add a condition before printing them.
String line = br.readLine();
while(line!=null){
if (line.startsWith("namespace") && line.endsWith("Console")){
System.out.println(line);
}
line = br.readLine();
}
这篇关于从文本文件中读取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文