In this example we will show how to export data to CSV file.
Source Code
1) ExportCSV.java
package com.beginner.examples;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class ExportCSV {
public static boolean exportCsv(File file, List dataList){
boolean isSucess=false;
FileOutputStream out=null;
OutputStreamWriter osw=null;
BufferedWriter bw=null;
try {
out = new FileOutputStream(file);
osw = new OutputStreamWriter(out);
bw =new BufferedWriter(osw);
if(dataList!=null && !dataList.isEmpty()){
for(String data : dataList){
bw.append(data).append("r");
}
}
isSucess=true;
} catch (Exception e) {
isSucess=false;
}finally{
if(bw!=null){
try {
bw.close();
bw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw!=null){
try {
osw.close();
osw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
out=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isSucess;
}
public static List importCsv(File file){
List dataList=new ArrayList();
BufferedReader br=null;
try {
br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
dataList.add(line);
}
}catch (Exception e) {
}finally{
if(br!=null){
try {
br.close();
br=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dataList;
}
}
2) CSVTest.java
package com.beginner.examples;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class CSVTest {
public static void main(String[] args) {
List dataList=new ArrayList();
dataList.add("1,Alice,female");
dataList.add("2,Bob,male");
dataList.add("3,Jack,male");
boolean isSuccess=ExportCSV.exportCsv(new File("E:tmpExportCSV.csv"), dataList);
System.out.println(isSuccess);
List dataList2=ExportCSV.importCsv(new File("E:\tmp\ExportCSV.csv"));
if(dataList!=null && !dataList.isEmpty()){
for(String data : dataList){
System.out.println(data);
}
}
}
}
Output:
true
1,Alice,female
2,Bob,male
3,Jack,male
References
Imported packages in Java documentation: