'How to skip a header line in a csv file using scanner?

This is my code so far:

public List<Entry> getEntries() throws FileNotFoundException {

        List<Entry> result = new ArrayList<>();
        Scanner scanner = new Scanner(new File("src/fp/sales/sales-data.csv"));

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            List<String> attributes = List.of(line.split("\t"));
            LocalDate date = LocalDate.parse(attributes.get(0), formatter);

            Entry entry = new Entry(date, attributes.get(1), attributes.get(2), attributes.get(3), Double.valueOf(attributes.get(5)));
            result.add(entry);
        }
        return null;
    }

I would like to skip the header line, because it won't work with it. How can I do this?



Solution 1:[1]

Answer by @Jhonny Mopp

public List<Entry> getEntries() throws FileNotFoundException {

        List<Entry> result = new ArrayList<>();
        Scanner scanner = new Scanner(new File("src/fp/sales/sales-data.csv"));
    String line = scanner.nextLine(); // ignore the first line of your file 
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            List<String> attributes = List.of(line.split("\t"));
            LocalDate date = LocalDate.parse(attributes.get(0), formatter);

            Entry entry = new Entry(date, attributes.get(1), attributes.get(2), attributes.get(3), Double.valueOf(attributes.get(5)));
            result.add(entry);
        }
        return null;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcio Rocha