techie_questie
techie_questie

Reputation: 1522

How to read CSV file from second line onwards

I am writing a small program in JAVA, where I am trying to read records from a CSV file. My CSV file has a static value in first line and comma separated values from second line onwards. I want to read the file that has employee records and show error if the file does not open or exist.

I know that to read a CSV file we use nextLine() like below-

 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

The issue is that my code will read file from first line onwards but the first line in the file is not a comma separated value. How can I ensure my file to read second line onwards?

Upvotes: 0

Views: 844

Answers (1)

Abra
Abra

Reputation: 20914

  1. Read first line of file and discard it.
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. Check if line contains comma
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(",");
            }
        }
    }
}

Note that above code uses try-with-resources

Upvotes: 1

Related Questions