Copy Code code as follows:
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 don't 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);
&NBSP;&NBSP}
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 ("Test Titile1");
Tmpl.add ("Test Titile2");
Source.add (Tmpl);
Writecsv (source);
Readcsv (New File ("D:\\/123.csv"));
}
}