繁体   English   中英

从文本文件中读取某些行

[英]Reading certain lines from text files

我想从文本文件中读取第1,第4,第7等(每3行),但是由于nextLine()会顺序读取所有内容,因此我不确定如何去做。 谢谢你的建议?

Scanner in2 = new Scanner(new File("url.txt"));

while (in2.hasNextLine()) {
    // Need some condition here
    String filesURL = in2.nextLine();
}

使用计数器和% (模)运算符,以便仅每三行读取一次。

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);
    }
}

阅读每一行,但仅处理每三行:

int lineNo = 0;
while (in2.hasNextLine()) {
    String filesURL = in2.nextLine();
    if (lineNo == 0)
        processLine (filesURL);
    lineNo = (lineNo + 1) % 3;
}

lineNo = (lineNo + 1) % 3将循环lineNo0,1,2,0,1,2,0,1,2,...并且仅在零时处理行(因此,第1、4行,7,...)。

如果您还没有索引来告诉您文件偏移量,该偏移量是文件中每一行的开始位置,那么查找每一行的唯一方法是依次读取文件。

您确定目标不只是/ output /第1,第4,第7等行吗? 您可以按顺序阅读所有行,但仅保留您感兴趣的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM