我想从文本文件中读取第1,第4,第7等(每3行),但我不知道如何继续这样做,因为nextLine()按顺序读取所有内容.谢谢你的建议?
Scanner in2 = new Scanner(new File("url.txt"));
while (in2.hasNextLine()) {
// Need some condition here
String filesURL = in2.nextLine();
}
Run Code Online (Sandbox Code Playgroud)
使用计数器和%(模数)运算符,因此只读取每三行.
Scanner in = new Scanner(new File("url.txt"));
int i = 1;
while (in.hasNextLine()) {
// Read the line first
String filesURL = in.nextLine();
/*
* 1 divided by 3 gives a remainder of 1
* 2 divided by 3 gives a remainder of 2
* 3 divided by 3 gives a remainder of 0
* 4 divided by 3 gives a remainder of 1
* and so on...
*
* i++ here just ensures i goes up by 1 every time this chunk of code runs.
*/
if (i++ % 3 == 1) {
// On every third line, do stuff; here I just print it
System.out.println(filesURL);
}
}
Run Code Online (Sandbox Code Playgroud)
您阅读每一行但只处理每三行一次:
int lineNo = 0;
while (in2.hasNextLine()) {
String filesURL = in2.nextLine();
if (lineNo == 0)
processLine (filesURL);
lineNo = (lineNo + 1) % 3;
}
Run Code Online (Sandbox Code Playgroud)
在lineNo = (lineNo + 1) % 3将循环lineNo通过0,1,2,0,1,2,0,1,2,...时,它的线与将仅被处理零(因此线1,4,7,...).