简体   繁体   中英

How do i start scanning from the second row of my CSV data to linked list?

So my CSV file contains something like in excel

     speed period warning pair
 1     26     1      1      1
 2     26     1      1      1
 3     26     1      1      1
 4     26     1      1      1

In my scanner file i have

public class scanner {

    public static void main(String[] args) throws IOException {
        // open file input stream
        BufferedReader reader = new BufferedReader(new FileReader(
                "amis.csv"));

        // read file line by line
        String line = null;
        Scanner scanner = null;
        int index = 0;
        List<amis> empList = new ArrayList<>();

        while ((line = reader.readLine()) != null) {
            amis emp = new amis();
            scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while (scanner.hasNext()) {
                String data = scanner.next();
                if (index == 0) {
                    emp.setId(data);
                } else if (index == 4) {
                    emp.setPair(data);
                } else if (index == 3) {
                    emp.setWarning(data);
                } else if (index == 2) {
                    emp.setPeriod(data);
                }else if (index == 1) {
                    emp.setSpeed(data);
                }else {
                    System.out.println("invalid data::" + data);
                }
                index++;
            }
            index = 0;
            empList.add(emp);
        }

        //close reader
        reader.close();

        System.out.println(empList);

    }

But the output of my linked list will show

ID=""::Pair="pair"::Warning="warning"::Period="period"::Speed="speed",

ID="1"::Pair=1::Warning=1::Period=1::Speed=26,

ID="2"::Pair=1::Warning=1::Period=1::Speed=26,

ID="3"::Pair=1::Warning=1::Period=1::Speed=26,

ID="4"::Pair=1::Warning=1::Period=1::Speed=26,

How to i just start from the second row.

You can just call scanner.nextLine before while loop, eg:

String headers = reader.nextLine();
while ((line = reader.readLine()) != null) {

This is what the documentation says:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

So, in the while loop, you will get all the lines from second line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM