使用commons-csv生成.csv文件

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

做个代码笔记,方便以后看。

commons-csv-1.1.jar的源码:https://github.com/apache/commons-csv

CsvFileBuilder.java类

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"};	
	
	private static FileWriter fileWriter = null;
	private static CSVPrinter csvPrinter = null;
	private static CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator('\n');  // 每条记录间隔符
	
	public static void write(Map info) {
		File file = new File("test.csv");	
		System.out.println(file.getAbsolutePath());
		try {											
			if (!file.exists()) {
				fileWriter = new FileWriter("test.csv",true);  // 创建test.csv的字符输出流		
				csvPrinter = new CSVPrinter(fileWriter, csvFormat);
				csvPrinter.printRecords(header);  // 生成.csv表的字段名
				System.out.println("执行");
			}else {
				fileWriter = new FileWriter("test.csv",true);  // 创建test.csv的字符输出流		
				csvPrinter = new CSVPrinter(fileWriter, csvFormat);
				System.out.println("文件存在");
			}
							
			Set ids = info.keySet();			
			for (String id : ids) {
				List idName = new ArrayList();
				idName.add(id);
				idName.add(info.get(id));
				csvPrinter.printRecord(idName);  // 向.csv文件中添加记录数据
			}
			System.out.println("生成.csv文件");
		}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();
			}			
		}
		
	}
}

测试类:

package com.huihui.main;

import java.util.HashMap;
import java.util.Map;

public class TestCsvFileBuilder {
	public static void main(String[] args) {
		
		Map idName = new HashMap();
		idName.put("1", "Java");
		idName.put("2", "C++");
		idName.put("3", "Python");
		idName.put("4", "Ruby");
		
		CsvFileBuilder.write(idName);
	}
}


源码+jar包(在源码的lib文件下)下载地址:http://pan.baidu.com/s/1ntBY2ud

转载于:https://my.oschina.net/liuchunhui/blog/478520

你可能感兴趣的:(使用commons-csv生成.csv文件)