![](/img/trans.png)
[英]Skip certain number of lines while reading a text file - BufferedReader Java
[英]Java filereader bufferedreader printing out a certain number of lines
我正在嘗試在Java中使用文件讀取器和緩沖讀取器,以從txt文件打印一定數量的行。 該文件有超過100000行,但我只想打印前100行。
我提出的代碼如下所示:
public class main {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("words.txt");
BufferedReader br = new BufferedReader(fr);
String s;
int count = 0;
while (count <101)
{
while((s = br.readLine()) != null)
{
System.out.println(s);
count++;
System.out.println(count);
}
}
fr.close();
}
}
它輸出如下內容:
it
1
was
2
a
3
sunny
4
day
...
依此類推(正在打印的整數只是為了讓我看到計數器在遞增)。 問題是,它一直到文件末尾,而不是在文本的第100行之后停止。 我的問題是,在第100行之后如何停止打印?
提前致謝。
您需要結合您的條件
while (count < 100 && (s = br.readLine()) != null) { ...
(編輯:約翰布克提到計數檢查應< 100
)
好吧,您的內部循環一直運行到文件末尾。您必須捕獲條件並嘗試打印101行,而不是100行 。 要打印100行,您需要檢查c <100,因為count初始化為'0'
while ( count < 100 && (s = br.readLine()) != null) {
System.out.println(s);
count++;
}
實際上,只是個猜測-但我可以嘗試結合兩個條件:
while ((s = br.readLine()) != null && count < 100)
System.out.println(s + " [line: "+(count++)+"]");
也許?
您不想使用嵌套的while循環,而是想要
while(count < 101 && (s = br.readLine()) != null){
一旦達到計數,這將停止文件讀取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.