你知道csv中如何输出英文双引号吗?
1、先上个预期的结果图:
结果文件有三列,表头分别为id,Name,Desc
2、再上一段希望生成上述csv的代码:
package chapter4;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by MyWorld on 2016/3/23.
*/
public class CsvWriteWithDoubleQuotation {
public static void main(String[] args) throws IOException {
List<Peron> source = getResult();
CsvWriteWithDoubleQuotation csvWriter = new CsvWriteWithDoubleQuotation();
csvWriter.write(source);
}
private void write(List<Peron> source) throws IOException {
File file = new File("resultWithDoubleQuotation.csv");
System.out.println(file.getAbsolutePath());
FileWriter fw = new FileWriter(file);
String title = "id,Name,Desc";
fw.write(title + "\n");
for (Peron peron : source) {
fw.write(String.format("%s,%s,\"%s\"\n", peron.getId(), peron.getName(), peron.getDesc()));
}
fw.flush();
fw.close();
}
private static List<Peron> getResult() {
List<Peron> source = new ArrayList<Peron>();
source.add(new Peron(1, "Tom", "I li kui, nicknamed \"black tornado\""));
source.add(new Peron(2, "Jim", "I'm Jim"));
source.add(new Peron(3, "John", "I'm John,twenty years old."));
return source;
}
}
class Peron {
private final int id;
private final String name;
private final String desc;
public Peron(int id, String name, String desc) {
this.id = id;
this.name = name;
this.desc = desc;
} public int getId() {
return id;
} public String getName() {
return name;
}
public String getDesc() {
return desc;
}
}
3、执行上述代码,
看看生成的结果文件是否与预期相同
咦,怎么与预期的不是很一样了啊,左边的双引号怎么到后面了?
4、id,Name,Desc
1,Tom,"I li kui, nicknamed "black tornado""
2,Jim,"I'm Jim"
3,John,"I'm John,twenty years old."
5、分析下原因:
与预期输出不一致的一行:
1,Tom,"I li kui, nicknamed "black tornado""
貌似前面"I li kui, nicknamed "是正常输出了,后面的两个双引号""照原样输出了
原来,csv默认由英文双引号("")括起来的内容是一个字段, 如果字符串放在英文双引号中,字符串中的内容除英文双引号外,都会按原样输出。
那么,我们这次要输出的双引号呢?
csv中约定,字段里连续两个双引号""显示成一个
更改下代码:
Code:
source.add(new Peron(1, "Tom", "I li kui, nicknamed \"\"black tornado\"\""));
source.add(new Peron(2, "Jim", "I'm Jim.\nAnd I'm a good boy."));
6、看看生成的结果与实际是否一致
是一致的!!
OK