make a code note, easy to see later.
Commons-csv-1.1.jar Source:https://github.com/apache/commons-csv
Csvfilebuilder.java class
Package Com.huihui.main;import Java.io.file;import Java.io.filewriter;import java.io.ioexception;import Java.util.arraylist;import Java.util.list;import Java.util.map;import Java.util.set;import Org.apache.commons.csv.csvformat;import Org.apache.commons.csv.csvprinter;public class CsvFileBuilder {private Static final string[] Header = {"id", "name"};p rivate static FileWriter FileWriter = null;private static Csvprinter CSVPR Inter = null;private static Csvformat Csvformat = CSVFormat.DEFAULT.withRecordSeparator (' \ n '); Each record delimiter public static void write (map<string, string> info) {File File = new file ("Test.csv"); System.out.println (File.getabsolutepath ()); try {if (!file.exists ()) {fileWriter = new FileWriter ("Test.csv", true); Create test.csv character output stream csvprinter = new Csvprinter (FileWriter, Csvformat); Csvprinter.printrecords (header); Generate A. csv table field name System.out.println ("Execute");} else {fileWriter = new FileWriter ("Test.csv", true); Create test.csv character output stream csvprinter = new Csvprinter (FileWriter, CSVFormat); System.out.println ("file exists");} set<string> ids = Info.keyset (); for (String id:ids) {list<string> idname = new ArrayList (); Idname.add (ID); ID Name.add (Info.get (ID)); Csvprinter.printrecord (Idname); Add the Record Data}system.out.println ("Generate a. csv file") to the. csv file;} catch (IOException e) {e.printstacktrace ();} catch (Exception e) {e.printstacktrace ();} Finally {try {csvprinter.flush (); Filewriter.flush (); Filewriter.close (); Csvprinter.close ();} catch (Exception e) {e.printstacktrace ();}}}}
Test class:
Package Com.huihui.main;import Java.util.hashmap;import Java.util.map;public class Testcsvfilebuilder {public static void Main (string[] args) {map<string, string> idname = new HashMap (); Idname.put ("1", "Java"); Idname.put ("2", "C + +" ); Idname.put ("3", "Python"); Idname.put ("4", "Ruby"); Csvfilebuilder.write (Idname);}}
Source +jar Package (under Lib file of source code):Http://pan.baidu.com/s/1ntBY2ud
Using Commons-csv to generate a. csv file