java生成csv文件亂碼的解決方法示例 java導(dǎo)出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("測(cè)試titile1");
tmpL.add("測(cè)試titile2");
source.add(tmpL);
writeCsv(source);
readCsv(new File("d:\\/123.csv"));
}
}
相關(guān)文章
Java?BasePooledObjectFactory?對(duì)象池化技術(shù)的使用
這篇文章主要介紹了Java?BasePooledObjectFactory?對(duì)象池化技術(shù),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04詳解spring batch的使用和定時(shí)器Quart的使用
spring Batch是一個(gè)基于Spring的企業(yè)級(jí)批處理框架,它通過(guò)配合定時(shí)器Quartz來(lái)輕易實(shí)現(xiàn)大批量的數(shù)據(jù)讀取或插入,并且全程自動(dòng)化,無(wú)需人員管理2017-08-08分布式醫(yī)療掛號(hào)系統(tǒng)EasyExcel導(dǎo)入導(dǎo)出數(shù)據(jù)字典的使用
這篇文章主要為大家介紹了分布式醫(yī)療掛號(hào)系統(tǒng)EasyExcel導(dǎo)入導(dǎo)出數(shù)據(jù)字典的使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04詳解java中的6種單例寫(xiě)法及優(yōu)缺點(diǎn)
在java中,單例有很多種寫(xiě)法,面試時(shí),手寫(xiě)代碼環(huán)節(jié),除了寫(xiě)算法題,有時(shí)候也會(huì)讓手寫(xiě)單例模式,這里記錄一下單例的幾種寫(xiě)法和優(yōu)缺點(diǎn)。需要的朋友可以參考下2018-11-11