Search code examples
javacsvbufferedreader

getting alternate column names while reading a line using buffered reader in java?


I am using this code to read a line in csv and get the column names,but the problem is I am getting alternate cloumn names.It is skipping the first column reading the second and then skipping the third and reading the fourth..

BufferedReader br = new BufferedReader(new FileReader(csvFile));
               String line = "";
               StringTokenizer st = null;

               int lineNumber = 0; 
               int tokenNumber = 0;



               //read comma separated file line by line
               while ((line = br.readLine()) != null) {
                 lineNumber++;

                 //use comma as token separator
                 st = new StringTokenizer(line, ",");


                 while (st.hasMoreTokens()) {
                   //tokenNumber++;
                   s.add(st.nextToken());
                   //display csv values
                   System.out.print(st.nextToken() + "  ");

                 }

Solution

  • You are calling st.nextToken() twice in the while loop. Each time, it will grab the next element.

    You may want to replace the StringTokenizer with line.split(",") unless you have a particular need to use it (such as performance).