使用扫描仪开始从特定行读取

时间:2016-08-07 17:09:47

标签: java java.util.scanner

无论如何使用Scanner开始从给定的行读取文件。

我想从第二行开始读到文件末尾并排除第一行。

我已尝试过这一行,但它不起作用

String line = input.next("pass the line that I want to start reading from");

请帮助

谢谢

2 个答案:

答案 0 :(得分:1)

您实际上可以创建一个方法来跳过文件的前N行,然后正常读取文件。

以下是一个例子:

import java.io.File;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        try {
            Scanner s = new Scanner(new File("input.txt"));
            skipLines(s, 3);//skip 3 lines of input.txt file
            //read the rest of the file
            while (s.hasNextLine()) {
                String line = s.nextLine();
                // use lines here
                System.out.println(line);
            }
        }catch (Exception e){
        }
    }

    public static void skipLines(Scanner s,int lineNum){
        for(int i = 0; i < lineNum;i++){
            if(s.hasNextLine())s.nextLine();
        }
    }
}

INPUT.TXT:

1
2
3
4
5
6
7
8
9
10

输出:

4
5
6
7
8
9
10

答案 1 :(得分:0)

使用一个布尔值来捕获导致读取值开始的“起始”值的时刻。

public static final int STARTER = "3";

public static void main(String[] args) {
    boolean read = false;
    try {
        Scanner s = new Scanner(new File("input.txt"));
        while (s.hasNextLine()) {
            String line = s.nextLine();
            if (!read) {
                if (Integer.parseInt(line) == STARTER) {
                    read = true;
                }
            } else {
                System.out.println(line); // or save to a list or ...
            }
        }
    } catch (Exception e){
        System.out.println(e);
    }
}