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

半世苍凉 提交于 2019-12-01 09:38:33

问题


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.

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?


回答1:


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




回答2:


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

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



回答3:


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


来源:https://stackoverflow.com/questions/13222025/how-to-ignore-first-line-of-txt-when-using-scanner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!