如何从第二行开始读取CSV文件



我正在用JAVA编写一个小程序,试图从CSV文件中读取记录。我的CSV文件在第一行有一个静态值,从第二行开始有逗号分隔的值。我想读取有员工记录的文件,如果该文件不打开或不存在,则显示错误。

我知道要读取CSV文件,我们使用nextLine((,如下所示-

public static Employee readData(String filename){

File file = new File(filename);
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String csvFileValue = scanner.nextLine();
String[] lines = csvFileValue.split(",");
}
} catch (FileNotFoundException e) {
throw e;
}
Employee.java-
public class Employee {
private String year;
ArrayList<Employee> employeeList = new ArrayList<>();
public Employee() {
year = "2020";
}
public Employee(String year, ArrayList<Employee> employeeList) {
this.year = year;
this.employeeList = employeeList;
}
}

CSV file-
2020
John, Smith, 28, 05-08-1992
Kate, Adams, 29, 05-08-1991

问题是,我的代码将从第一行开始读取文件,但文件中的第一行不是逗号分隔的值。如何确保我的文件从第二行开始读取?

  1. 读取文件的第一行并丢弃它
public static Employee readData(String filename) throws IOException {
File file = new File(filename);
try (Scanner scanner = new Scanner(file)) {
if (scanner.hasNextLine()) {
// Read first line of file and discard it.
scanner.nextLine();
}
while (scanner.hasNextLine()) {
String csvFileValue = scanner.nextLine();
String[] lines = csvFileValue.split(",");
}
}
}

  1. 检查行是否包含逗号
public static Employee readData(String filename) throws IOException {
File file = new File(filename);
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String csvFileValue = scanner.nextLine();
// Only handle 'csvFileValue' if it contains a comma.
if (csvFileValue.contains(",") {
String[] lines = csvFileValue.split(",");
}
}
}
}

注意,上面的代码使用try with resources

最新更新