java 使用 Scanner 类时如何忽略 .txt 的第一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13222025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:56:19  来源:igfitidea点击:

How to ignore first line of .txt when using Scanner class

javajava.util.scanner

提问by iggy2012

I have a text file that reads:

我有一个文本文件,内容如下:

Description|SKU|Retail Price|Discount
Tassimo T46 Home Brewing System|43-0439-6|17999|0.30
Moto Precise Fit Rear Wiper Blade|0210919|799|0.0

I've got it so that I read everything, and it works perfectly, save for the fact that it reads the first line, which is a sort of legend for the .txt file, which must be ignored.

我已经有了它,所以我可以阅读所有内容,它运行得很好,除了它读取第一行的事实,这是 .txt 文件的一种图例,必须被忽略。

public static List<Item> read(File file) throws ApplicationException {
    Scanner scanner = null;
    try {
        scanner = new Scanner(file);
    } catch (FileNotFoundException e) {
        throw new ApplicationException(e);
    }

    List<Item> items = new ArrayList<Item>();

    try {
        while (scanner.hasNext()) {
            String row = scanner.nextLine();
            String[] elements = row.split("\|");
            if (elements.length != 4) {
                throw new ApplicationException(String.format(
                        "Expected 4 elements but got %d", elements.length));
            }
            try {
                items.add(new Item(elements[0], elements[1], Integer
                        .valueOf(elements[2]), Float.valueOf(elements[3])));
            } catch (NumberFormatException e) {
                throw new ApplicationException(e);
            }
        }
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }

    return items;
}

How do I ignore the first line using the Scanner class?

如何使用 Scanner 类忽略第一行?

回答by awolfe91

Simply calling scanner.nextLine() once before any processing should do the trick.

在任何处理之前简单地调用一次scanner.nextLine() 就可以了。

回答by PermGenError

how about calling scanner.nextLine() as outside your loop.

在循环之外调用scanner.nextLine() 怎么样。

scanner.nextLine();//this would read the first line from the text file
 while (scanner.hasNext()) {
            String row = scanner.nextLine();

回答by iabdalkader

scanner.nextLine();
while (scanner.hasNext()) {
      String row = scanner.nextLine();
      ....