java生成csv文件亂碼的處理辦法示例 java導出csv亂碼。本站提示廣大學習愛好者:(java生成csv文件亂碼的處理辦法示例 java導出csv亂碼)文章只能為提供參考,不一定能成為您想要的結果。以下是java生成csv文件亂碼的處理辦法示例 java導出csv亂碼正文
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.谷歌.common.base.Charsets;
import com.谷歌.common.base.Joiner;
import com.谷歌.common.base.Preconditions;
import com.谷歌.common.collect.Lists;
import com.谷歌.common.io.Files;
import com.谷歌.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"));
}
}