在往csv文件中写入内容的时候,习惯性的指定了utf-8编码,原以为啥事都没有,但是打开文件的时候,一下子就懵逼了
具体代码如下:
public static void main(String[] args) throws Exception {
File file = new File( "D:/country.csv");
if (! file.exists()) {
file.createNewFile();
}
OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(file ), "UTF-8" );
BufferedWriter bw = new BufferedWriter( out);
try {
String path = writeCSV.class .getResource("LocList.xml" ).getPath();
SAXReader reader = new SAXReader();
try {
Document document = reader.read(path);
Element rootElement = document.getRootElement();
Iterator< Element> iterator = rootElement.elementIterator();
Element ele = null;
while ( iterator.hasNext()) {
ele = iterator.next();
String country = ele.attributeValue( "Name");
List< Element> provinces = ele.elements();
if ( provinces == null || provinces.isEmpty()) {
writeCSVLine(country, country, country, bw);
continue;
}
for ( Element pe : provinces) {
String province = pe.attributeValue( "Name");
if ( StringUtils.isEmpty(province)) {
province = country;
}
List< Element> cities = pe.elements();
if ( cities == null || cities.isEmpty()) {
writeCSVLine(country, province, province, bw);
continue;
}
for ( Element ce : cities) {
String city = ce.attributeValue( "Name");
if ( StringUtils.isEmpty(city)) {
city = province;
}
writeCSVLine(country, province, city, bw);
}
}
}
System. out.println( "写入成功!" );
}
catch (Exception e) {
return;
}
}
finally {
bw.close();
}
}
public static void writeCSVLine(String country, String province, String city, BufferedWriter bw)
throws IOException {
StringBuilder sb = new StringBuilder();
sb.append( country).append( ',').append( province).append( ',').append( city);
bw.write(sb.toString());
bw.newLine();
}
既然utf-8不行,那我们试试gb2312?
说干就干,修改代码如下:
OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(file), "gb2312" );
run as...然而,现实又一次无情的摧残着我,还是不行,没办法,那就挨个都试一遍吧,试试gbk
OutputStreamWriter out = new OutputStreamWriter( new FileOutputStream(file), "gbk" );
等待着,终于,打开文件的那刹那,没看到乱码,欧耶~
那么问题来了,为什么要用gbk呢?这三者有什么区别?
http://www.cnblogs.com/xiaomia/archive/2010/11/28/1890072.html 这篇文章很详细的解释了这几者的区别和联系。