zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JAVA导出成CSV文件详解编程语言

2023-06-13 09:20:30 时间
// csvs 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")); }

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10982.html

cgojava