发布于 2016-07-09 04:05:53 | 406 次阅读 | 评论: 1 | 来源: 网友投递

这里有新鲜出炉的Java函数式编程,程序狗速度看过来!

Java程序设计语言

java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。


这篇文章主要介绍了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"));
 }
}



最新网友评论  共有(1)条评论 发布评论 返回顶部
ofh 发布于2016-09-21 13:42:13
为啥我的不行啊
支持(0)  反对(0)  回复

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务