Parse CSV File using StringTokenizer example - Java File Path IO

Java examples for File Path IO:CSV File

Description

Parse CSV File using StringTokenizer example

Demo Code


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.StringTokenizer;
 
public class Main {
 
        public static void main(String[] args) {
               //from  ww w.  ja  v  a 2s  . c om
                try
                {
                        String strFile = "C:/Folder/example.csv";
                        BufferedReader br = new BufferedReader( new FileReader(strFile));
                        String strLine = "";
                        StringTokenizer st = null;
                        int lineNumber = 0, tokenNumber = 0;
                        while( (strLine = br.readLine()) != null)
                        {
                                lineNumber++;
                               
                                //break comma separated line using ","
                                st = new StringTokenizer(strLine, ",");
                               
                                while(st.hasMoreTokens())
                                {
                                        //display csv values
                                        tokenNumber++;
                                        System.out.println("Line # " + lineNumber +
                                                        ", Token # " + tokenNumber
                                                        + ", Token : "+ st.nextToken());
                                }
                                //reset token number
                                tokenNumber = 0;
                        }
                }
                catch(Exception e)
                {
                        System.out.println("Exception while reading csv file: " + e);                  
                }
        }
}

Result


Related Tutorials