Skip first line while reading CSV file in Java

前端 未结 8 2167
陌清茗
陌清茗 2021-02-15 00:30

I am writing a parser code to read a .csv file and parse it to XML. This is the code I have and it works, except I would like it to skip the first line in the file. So I decided

相关标签:
8条回答
  • 2021-02-15 00:48

    Create a variable interation and initialize with 0. Check it as very first thing in while loop.

    String line;
    int iteration = 0;
    while ((line = br.readLine()) != null) {
        if(iteration == 0) {
            iteration++;  
            continue;
        }
        ...
        ...
    }
    
    0 讨论(0)
  • 2021-02-15 00:49
    boolean isRecord = false;
    for (CSVRecord record : records) {
        if(isRecord){
            //process records here.
        }else{
            isRecord = true;
        }
    }
    

    Instead of adding counter adding flag will not hit the performance.

    0 讨论(0)
  • 2021-02-15 00:56

    I am rather confused by your code, your have the lineMap and you also have fw (whatever that is). Which one are you using? You say you want to skip the first line, but you don't

    if (firstLine == true) {
       firstLine = false;
       continue;
    }
    

    I would also suggest using a library like CSVReader which I belive even has a property ignoreFirstLine

    http://opencsv.sourceforge.net/apidocs/au/com/bytecode/opencsv/CSVReader.html

    0 讨论(0)
  • 2021-02-15 01:02

    why don't you just use the for loop

    for(int i=1; (line = br.readLine()) != null; i++)
    {
        //Your code
    }
    
    0 讨论(0)
  • 2021-02-15 01:04

    For skipping first line(which normally contains header of the columns) take a variable and increase this variable in while loop at first place, and continue;

    int lineNumber = 0;
    
    and then in while loop 
    
    while ((line = br.readLine()) != null) {
                            if(lineNumber == 0) {
                                lineNumber++;
                                continue;
                            }
                            lineNumber++;
    
                           //do waterver u have to do with the tokens in this line(second line)
    
                }
    
    0 讨论(0)
  • 2021-02-15 01:08

    Use buffer reader two times, like this:

    while ((line = br.readLine()) != null) {
      while ((line = br.readLine()) != null) {
        //your code                     
      }
    }
    
    0 讨论(0)
提交回复
热议问题