Tuesday, September 15, 2009

how to read a csv file using java

//class to read CSV file :

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.StringTokenizer;

public class readCSV

{ //readCSV class starts here

public static void main(String args[]) throws IOException

{ //main method starts

String fName = "test1.csv";//csv file which u wanna read

String thisLine; //string variable which take each record at a time

int count=0; //to count no. of records

FileInputStream fis = new FileInputStream(fName);
//A FileInputStream obtains input bytes from a file in a file system

DataInputStream myInput = new DataInputStream(fis);
/*data input stream lets an application read primitive Java data types
from an underlying input stream in a machine-independent way*/

while ((thisLine = myInput.readLine()) != null)
{ //beginning of outer while loop
StringTokenizer st =new StringTokenizer(thisLine,",");
while(st.hasMoreElements()){
String field = st.nextToken();
System.out.print(field+", ");
}
System.out.println();

} //ending of outer while loop
} //main method ends
} //readCSV class ends here

No comments: