2012-11-04 162 views
1

时,如何忽略.TXT的第一行我有一个文本文件,上面写着:使用扫描仪类

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文件的一种图例,必须忽略它。

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类的第一行?

+1

刚刚火while循环前的空'scanner.nextLine'? –

+1

在处理之前调用nextLine()函数一次。 – Annabelle

回答

4

在进行任何处理之前,只需调用scanner.nextLine()一次即可实现。

2

如何将scanner.nextLine()作为外部循环调用。

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