我想从文件中打印特定行,例如第四行或第二行。这是我的代码,它只显示所有行和每行号。如果这是一个简单而愚蠢的问题,我很抱歉,但提前谢谢你:D。
FileReader fr = null;
LineNumberReader lnr = null;
String str;
int i;
try{
// create new reader
fr = new FileReader("test.txt");
lnr = new LineNumberReader(fr);
// read lines till the end of the stream
while((str=lnr.readLine())!=null)
{
i=lnr.getLineNumber();
System.out.print("("+i+")");
// prints string
System.out.println(str);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}finally{
// closes the stream and releases system resources
if(fr!=null)
fr.close();
if(lnr!=null)
lnr.close();
}
}
}
最佳答案
最简单的方法就是简单地跟踪您正在阅读的行。看起来您想使用 i
为了那个原因。别忘了break
一旦你读完你想要的行就退出循环。
此外, continue 语句表示“跳过其他所有内容并移至下一个迭代”。
参见The while and do-while Statements
while((str=lnr.readLine())!=null)
{
i=lnr.getLineNumber();
if(i != 57) continue;
System.out.print("("+i+")");
// prints string
System.out.println(str);
break;
}
请记住,正如下面的评论提到的,LineNumberReader 从 0
开始读取。 。因此,这实际上会按自然顺序返回第 56 行。如果您想要自然排序的 57,则可以使用此条件语句。
if(i <= 57) continue;
关于java - 使用 java 的文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26354774/