How to Parse CSV File in Java


This example will help us learn how to parse comma separated file (CSV file) with StringTokenizer and BufferedReader classes in Java.

Source Code

package com.beginner.examples;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.util.StringTokenizer;

public class ParseCSVUseStringtokenizer {

	public static void main(String[] args) {

		try {
			// Read a CSV file
			Reader reader = new FileReader("test.csv");

			// Use the wrapper flow
			BufferedReader buffReader = new BufferedReader(reader);

			// Declare a string variable to read line by line
			String line = null;

			// Declare a Boolean variable in order to print only one line of serial Numbers
			boolean b = true;
			
			//A vertical ordinal
			int rowVertical = 0;
			
			//Read line by line
			while ((line = buffReader.readLine()) != null) {
				//Create the StringTokenizer object
				StringTokenizer tokenizer = new StringTokenizer(line);
				
				//Horizontal serial number
				int rowHorizontal = 0;
				
				//This is used to store tokens
				StringBuilder sb = new StringBuilder();
				
				while (tokenizer.hasMoreElements()) {
					//Calculate the number of tokens
					rowHorizontal++;
					
					sb.append(tokenizer.nextToken(",") + "t");

				}
				
				//Print a line of serial Numbers
				if (b) {
					System.out.print("Table" + "t");
					for (int i = 1; i <= rowHorizontal; i++) {
						System.out.print(i + "t");
					}
					b = false;
				}
				System.out.println();
				
				System.out.print((++rowVertical) + "t" + sb.toString());
			}

		} catch (Exception e) {

			e.printStackTrace();
		}

	}

}

Output:

![](Output.png)

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments