從csv

2017-02-28 50 views
0

中排除標題我有一個.csv文件,其中包含我希望跳過的標題。當頭文件存在於.csv文件中時,出現錯誤,但當它被刪除時,程序運行得非常好。我希望我的代碼跳過標題並繼續處理。從csv

什麼的.csv文件看起來像:

品牌型號快速的燃油BaseMPG比例因子時間走遍

福特野馬0 20.2 20 2.3 0.02

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 

public class Test { 

    public static void main(String[] args) throws IOException { 
    List<Vehicle> cars = new ArrayList<Vehicle>(); 
    Scanner scanner = new Scanner(System.in); 
    System.out.println("Enter the file name:"); 
    String filename = scanner.nextLine(); 
    BufferedReader reader = new BufferedReader(new FileReader(new File(
      filename.trim()))); 
    String line = ""; 


    while ((line = reader.readLine()) != null) { 
     String[] words = line.split(","); 


      String make = words[0]; 
      String model = words[1]; 
      int currentSpeed = Integer.parseInt(words[2]); 
      double fuel = Double.parseDouble(words[3]); 
      double baseMpg = Double.parseDouble(words[4]); 
      double scaleFactor = Double.parseDouble(words[5]); 
      double timeTravelled = Double.parseDouble(words[6]); 

      Vehicle car = new Car(fuel, currentSpeed, baseMpg, scaleFactor, 
        make, model, timeTravelled); 
      System.out.println(car); 
      cars.add(car); 


    } 

    FileWriter writer=new FileWriter(new File("ProcessedCars.txt")); 

    for(Vehicle car:cars) 
    { 
     writer.write(car.toString()); 
     writer.flush(); 
     writer.write("\r\n"); 

     } 

    } 

} 

回答

0

一種方式來做到這一點是趕上例外:

try{ 
     int currentSpeed = Integer.parseInt(words[2]); 
     // ... 
    }catch(NumberFormatException e){ 
     // Failed to parse speed, input is likely a text, like header 
    } 

或者,如果您確定有hea der,只需在循環之前調用額外的readline()即可。

+0

爲什麼我在線程得到異常 「主要」 java.lang.ArrayIndexOutOfBoundsException:1 \t在Test.main(Test.java:27) – TechGeek

1

跳過第一行while循環:

boolean skip = true; 
while ((line = reader.readLine()) != null) { 
    if(skip) { 
    skip = false; // Skip only the first line 
    continue; 
    } 
    String[] words = line.split(","); 
    // ... 
} 
+0

線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:1 \t at Test.main(Test.java:27) – TechGeek

+0

第27行是什麼行? – vanje

+0

您的輸入文件的一行可能列數少於預期。在這種情況下,單詞數組的長度小於7,然後'單詞[6]'導致ArrayIndexOutOfBoundsException異常。 – vanje