JAVA导出成CSV文件
发布时间:2020-05-24 15:48:18 所属栏目:Java 来源:互联网
导读:JAVA导出成CSV文件
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 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 = "rn";
// 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"));
}
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
