我想从文本文件中读取第1,第4,第7等(每3行)但不知道如何这样做,因为nextLine()按顺序读取所有内容。谢谢你的建议?
Scanner in2 = new Scanner(new File("url.txt"));
while (in2.hasNextLine()) {
// Need some condition here
String filesURL = in2.nextLine();
}
答案 0 :(得分:8)
使用计数器和%
(模数)运算符,因此只读取每三行。
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);
}
}
答案 1 :(得分:5)
您读取每一行,但每隔一行只有进程:
int lineNo = 0;
while (in2.hasNextLine()) {
String filesURL = in2.nextLine();
if (lineNo == 0)
processLine (filesURL);
lineNo = (lineNo + 1) % 3;
}
lineNo = (lineNo + 1) % 3
会循环lineNo
到0,1,2,0,1,2,0,1,2,...
,只有当它为零时才会处理这些行(因此第1,4,7行......)。
答案 2 :(得分:2)
如果您还没有索引告诉您文件中每行开头的文件偏移量,那么查找每一行的唯一方法是按顺序读取文件。
你确定目标不只是输出/输出第1,第4,第7等等吗?您可以按顺序读取所有行,但只保留您感兴趣的行。