我想从设置行(在本例中为第13行)中读取并显示文本文件的内容,直到文本文件结束。 因此,如果文档有20行,则应显示第13行到第20行。问题是,此文档获取更多内容,因此应自动确定行数。
基本上,当没有更多内容时,它需要结束。如果我没有设置结束行,则输出为" null"永远。
try {
BufferedReader in = new BufferedReader (new FileReader("C://Users/Prakt1/Desktop/projektverwaltung.txt"));
String info = "";
int startLine = 13;
int endLine = 25;
System.out.println("");
for (int x = 0; x < startLine; x++) {
info = in.readLine();
}
for (int x = startLine; x < endLine + 1; x++) {
info = in.readLine();
System.out.println(info);
}
System.out.println("");
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
非常感谢你的帮助!
答案 0 :(得分:3)
使用类似的东西来设置循环。它将继续读取,直到遇到null,这将是文件的结尾。
while ((info = in.readLine()) != null)
答案 1 :(得分:2)
如果我理解你的问题,你可以用这样的东西来做 -
for (int x = 0; x < startLine; x++) {
info = in.readLine();
}
while ((info = in.readLine()) != null) {
System.out.println(info);
}
答案 2 :(得分:-1)
这样的事情应该有效:
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader("C://Users/Prakt1/Desktop/projektverwaltung.txt"));
String info = null;
int startLine = 13;
int lineNum = 0;
while ((info = in.readLine()) != null) {
lineNum++;
if (lineNum >= startLine) {
System.out.println(info);
}
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
in.close();
}
另外,请务必在finally块中关闭阅读器。
您可能还想查看LineNumberReader