使用Scanner类时如何忽略.txt的第一行 [英] How to ignore first line of .txt when using Scanner class

查看:106
本文介绍了使用Scanner类时如何忽略.txt的第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我已经得到它以便我阅读所有内容,并且它完美地工作,除了它读取第一行的事实,这是.txt文件的一种传说,必须被忽略。

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.

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

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

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

推荐答案

在执行任何处理之前,只需调用一次scanner .nextLine()就可以了。

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

这篇关于使用Scanner类时如何忽略.txt的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆