我有一个.csv文件,其中包含我想要跳过的标题。当.csv文件中存在标题时出现错误但是当它被删除时程序运行完全正常。我希望我的代码跳过标题并继续进行该过程。
.csv文件是什么样的:
使模型速度燃料基础MPG ScaleFactor时间移动
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");
}
}
}
答案 0 :(得分:1)
跳过while循环中的第一行:
boolean skip = true;
while ((line = reader.readLine()) != null) {
if(skip) {
skip = false; // Skip only the first line
continue;
}
String[] words = line.split(",");
// ...
}
答案 1 :(得分:0)
一种方法是捕获异常:
try{
int currentSpeed = Integer.parseInt(words[2]);
// ...
}catch(NumberFormatException e){
// Failed to parse speed, input is likely a text, like header
}
或者,如果您确定有标题,请在循环之前调用额外的readline()
。