Reputation: 1
I have a .csv file which has header that I would like to be skipped. I get error when the header is present in the .csv file but when it is removed program runs perfectly fine. I would like my code to skip the header and continue on with the process.
What the .csv files looks like:
Make Model Speed Fuel BaseMPG ScaleFactor Time Travelled
Ford Mustang 0 20.2 20 0.02 2.3
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");
}
}
}
Upvotes: 0
Views: 2208
Reputation: 10373
Skip the first line in your while loop:
boolean skip = true;
while ((line = reader.readLine()) != null) {
if(skip) {
skip = false; // Skip only the first line
continue;
}
String[] words = line.split(",");
// ...
}
Upvotes: 1
Reputation: 1405
One way to do it is to catch the exception:
try{
int currentSpeed = Integer.parseInt(words[2]);
// ...
}catch(NumberFormatException e){
// Failed to parse speed, input is likely a text, like header
}
Or, if you are sure there is a header, just call an extra readline()
before your loop.
Upvotes: 0