Ad

Friday 9 October 2009

To create and write data to CSV files in Java(using BufferedWriter)

CSV stands of comma separated values.csv files will have the data separated by the delimiter ','.we don't need to use the third party jars for writing data to the CSV files.A Simple straightforward approach is to use the BufferedWriter for writing data to csv files.Lets say we need to create a csv file which has employee details like employee id and name.
We can use the BufferdWriter for this as shown below

BufferedWriter br =new BufferedWriter(new FileWriter("D://test.CSV"));                                              
br.write("EMPID,EMPNAME");
br.write('\n');
br.write("E01,John");
br.write('\n');
br.write("E02,George");
br.close();


As shown in the above code,we used ',' delimiter to separate the data and '\n' operator to create the new line.when we run the above code,csv files will be generated in the specified directory and it will be as shown below

Saturday 3 October 2009

Enhanced for loop in Java 5(To iterate the Collection objects)

Prior to version java 5 ,we can use only the Iterator interface to iterate the collections .The below code sample show us the typical use of iterator interface.

List strlist = new ArrayList();
strlist.add("one");
strlist.add("two");
strlist.add("three");
Iterator it=strlist.iterator();
while(it.hasNext())
{
System.out.println("String in Collections---"+it.next());                                                                          
}


Output:
String in Collections---one
String in Collections---two
String in Collections---three

But from version java 5,we can use the Enhanced for loops to iterate the collections instead of using iterator interface.Enhanced for loops will make the code looks easier and simpler as shown below


List<String> strlist = new ArrayList<String>();                                                                                        
strlist.add("one");
strlist.add("two");
strlist.add("three");
for(String str:strlist)
{
System.out.println("String in Collections---"+str);
}


Output:
String in Collections---one
String in Collections---two
String in Collections---three