What is CSV files.
CSV stands for comma separated values. Sometimes in your application you have to take data from existing csv files as well. Here is how csv files looks.
CSV stands for comma separated values. Sometimes in your application you have to take data from existing csv files as well. Here is how csv files looks.
How to read CSV files
In this post we will
use some third party API called opencsv,
we can download this as jar file and can use existing methods to read file
download opencsv
using below link
This will come as rar file extract this then you will
find jar
Add that jar into
project
How to add jar
-Right click on project > Select Build path > Select configure build
path> Add external jar> now Select the jar which we downloaded
Steps How to read-
1- We have
predefined class called CSVReader, create an object and pass the csv file
path
2- call readAll()
method which will return the csv content in List<String[]>
3-using Iterator,
you can iterate all the values and use according to application
Program – How
to read CSV files using Java
package Others;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import
au.com.bytecode.opencsv.CSVReader;
public class csv {
public static void main(String[] args) throws Exception {
@SuppressWarnings("resource")
CSVReader
reader = new CSVReader(new FileReader("D:\\WebDriver\\Input\\abhi.csv"));
List<String[]>
li=reader.readAll();
System.out.println("Total rows
which we have is "+li.size());
Iterator<String[]>i1= li.iterator();
while(i1.hasNext())
{
String[]
str=i1.next();
System.out.print(" Values are
");
for(int i=0;i<str.length;i++)
{
System.out.println(" "+str[i]);
}
System.out.println("
");
}
}
}
No comments:
Post a Comment