环境依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.7</version>
</dependency>
将数据写入到 CSV文件
private final String[] header = new String[]{"deptno", "dname" ,"loc"};
private final String FILE_NAME = "H:\\source\\gitRep\\BigdataStudy\\Kylin\\Kylin\\data\\dept.csv";
CSVFormat csvFormat = CSVFormat.DEFAULT
.withHeader(header)
.withSkipHeaderRecord()
.withDelimiter('\t');
public void write_csv() throws IOException {
Appendable out = new PrintWriter("dept2.csv");
CSVPrinter csvPrinter = CSVFormat.DEFAULT.print(out);
List<String> records = new ArrayList<>();
records.add("RSA001_20190121" + "\t" + "产品部" + "\t" + "RSA001");
records.add("RSA002_20180623" + "\t" + "设计部" + "\t" + "RSA002");
records.add("RSA003_20150422" + "\t" + "技术部" + "\t" + "RSA003");
records.add("RSA004_20160903" + "\t" + "运营部" + "\t" + "RSA004");
records.add("RSA005_20120608" + "\t" + "财务部" + "\t" + "RSA005");
for (String record : records) {
csvPrinter.printRecord(record);
}
csvPrinter.flush();
csvPrinter.close();
}
从CSV文件中读取数据
private final String[] header = new String[]{"deptno", "dname", "loc"};
private final String FILE_NAME = "H:\\source\\gitRep\\BigdataStudy\\Kylin\\Kylin\\data\\dept.csv";
CSVFormat csvFormat = CSVFormat.DEFAULT
.withHeader(header)
.withSkipHeaderRecord()
.withDelimiter('\t');
public void read_csv() throws IOException {
Reader in = new FileReader(FILE_NAME);
CSVParser parser = csvFormat.parse(in);
List<CSVRecord> records = parser.getRecords();
for (CSVRecord record : records) {
String deptno = record.get("deptno");
String dname = record.get("dname");
String loc = record.get("loc");
System.out.println(deptno + "\t" + dname + "\t" + loc);
System.out.println(record);
}
parser.close();
in.close();
}
参考
- Apache Commons CSV User Guide