欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java生成csv文件乱码的解决方法示例 java导出csv乱码

程序员文章站 2024-02-23 13:37:22
复制代码 代码如下:import java.io.file;import java.io.ioexception;import java.util.list; impor...

复制代码 代码如下:

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"));
 }
}