欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-04-10 08:53:59|栏目:JAVA代码|点击:

复制代码 代码如下:

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

上一篇:JAVA8 的StringJoiner 使用及原理解析

栏    目:JAVA代码

下一篇:Spring Boot高效数据聚合之道深入讲解

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

本文地址:http://www.codeinn.net/misctech/98645.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有