skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Friday, October 5, 2012

Writing a Data to CSV file using Java

Posted by Raju Gupta at 11:01 PM – 0 comments
 
The Code snippet here talks more about generation of CSV Report in Java using external API (opencsv-1.8.jar). The main goal of this component is to generate a report and update the report with the existing data. This code is used in real time applications and the performance is very high.

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

 

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

 

public class JavatoCSV {

 public static void main(String[] args) {
  try {
    CSVReader reader = new CSVReader(new FileReader("c:\\Raju\\sample.csv"));
       List myEntries = reader.readAll();

       File f = new File("c:\\Raju\\sample.csv");
       f.delete();
        
    System.out.println(myEntries.size());
     
     String [] names ={"JAVA","Programming","Tutorial"};
     myEntries.add(names); 
    append(myEntries, names);   
         
  } catch (Throwable e){
  }
 } 
  public static void append(List list, String names1[]) {
  try {

   CSVWriter writer = new CSVWriter(new FileWriter("c:\\Raju\\sample.csv"));
   // feed in your array (or convert your data to an array)
   //String[] entries = "first#second#third".split("#");
   System.out.println(list.size());
    writer.writeAll(list);
          
    //writer.writeNext(names1);
    
   //writer.close();
  
   writer.close();

  } catch (Throwable e) {
   e.printStackTrace();
  }
 }  
}

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger