Search code examples
javaarrayscsvbufferedreader

deleting first line when reading csv in Java


I've read similar topics but havent found any which use this method of reading so I couldn't fix it.

How can I skip the first line when reading using the following method? BTW, I have trouble with the second read, after the line with:

File file = new File("attendance.csv");

Code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.Scanner;

public class ClassAttendance {

public static void main(String[] args) throws Exception {

            int rowCount = 0;
            int colCount = 0;

        Scanner rc = new Scanner(new File("attendance.csv"));
        while (rc.hasNextLine()) {
            rowCount++;
            rc.nextLine();
        }
        rc.close();

    File file = new File("attendance.csv");
    List<String> lines = Files.readAllLines(file.toPath(), 
            StandardCharsets.UTF_8);
    double sum = 0;
    double avg;
        for(int n=1; n<3; ++n){
            for (String line : lines) {
        String[] array = line.split(",");
        System.out.println(array[n]);

        sum = sum + Double.parseDouble(array[n]);
    }   
        avg = sum/rowCount;
        System.out.print("Week ");
        System.out.print(n);
        System.out.print("Average = ");
        System.out.print(avg);
        System.out.println();
    }

}
}

So far I tried putting:

List<String> headerLine = Files.readLine(file.toPath());

above the "readAllLines" line but it didn't work for me


Solution

  • Please try to replace the following lines:

    for (String line : lines) {
        String[] array = line.split(",");
    ...
    

    To these:

    for (int i=1; i<lines.size(); i++) {
        String[] array = lines.get(i).split(",");
    ...
    

    In this way we can skip reading the first line (as we initialize i=1 instead of "normal" i=0).