java生成csv文件乱码的解决方法示例 java导出csv乱码
import java.io.file;
import java.io.ioexception;
import java.util.list;
import com.google.common.base.charsets;
import com.google.common.base.joiner;
import com.google.common.base.preconditions;
import com.google.common.collect.lists;
import com.google.common.io.files;
import com.google.common.primitives.bytes;
public class fooutilscsvhelper {
// csv's default delemiter is ','
private final static string default_delimiter = ",";
// mark a new line
private final static string default_end = "\r\n";
// if you do not want a utf-8 ,just replace the byte array.
private final static byte commoncsvhead[] = { (byte) 0xef, (byte) 0xbb,
(byte) 0xbf };
/**
* write source to a csv file
*
* @param source
* @throws ioexception
*/
public static void writecsv(list<list<string>> source) throws ioexception {
// aoid java.lang.nullpointerexception
preconditions.checknotnull(source);
stringbuilder sbbuilder = new stringbuilder();
for (list<string> list : source) {
sbbuilder.append(joiner.on(default_delimiter).join(list)).append(
default_end);
}
files.write(bytes.concat(commoncsvhead,
sbbuilder.tostring().getbytes(charsets.utf_8.tostring())),
new file("d:\\/123.csv"));
}
/**
* simple read a csv file
*
* @param file
* @throws ioexception
*/
public static void readcsv(file file) throws ioexception {
system.out.println(files.readfirstline(file, charsets.utf_8));
}
// run a small test yourself.
public static void main(string[] args) throws ioexception {
list<list<string>> source = lists.newarraylist();
list<string> tmpl = lists.newarraylist();
tmpl.add("测试titile1");
tmpl.add("测试titile2");
source.add(tmpl);
writecsv(source);
readcsv(new file("d:\\/123.csv"));
}
}
上一篇: Unicode和Python的中文处理