Java-generated CSV file garbled solution Example Java export CSV garbled _java

Source: Internet
Author: User

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"));
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.