Remember once Java generated CSV file garbled solution process (GB2312 encoding)

Source: Internet
Author: User

System: Win7 (format: Chinese (Simplified, China))

Tools: Eclipse (default encoding Utf-8)

Two services: "RESTful interface" and "Service server".

Scenario: "Service Server" calls the "RESTful interface" multiple times, and each time the "RESTful interface" returns a generated CSV file content. Service server saves the CSV content returned by the "RESTful interface" to a CSV file each time. and package The resulting multiple CSV files into a single zip archive package.

"RESTful interfaces": Generating CSV files from a set of data

1. Java code generated CSV file, file output stream encoding set to "UTF-8" when the generated CSV file opened, Chinese garbled.

2. Set the file output stream encoding to "GB2312", when the generated CSV file is opened, the Chinese is not garbled.

The Java code is as follows:

    /*** Generate a. csv format file*/     Public Static BooleanCreatecsvfile (list<object[]>rows, String FilePath, String fileName) {        //Mark whether the file was generated successfully        BooleanFlag =true; //file output streamBufferedWriter FileOutputStream =NULL; Try {            //full path with file nameString FullPath = filePath + file.separator + fileName +constants.suffix_csv; File File=NewFile (FullPath); if(!file.getparentfile (). exists ()) {//If the parent directory does not exist, create a parent directoryfile.getparentfile (). Mkdirs (); }            if(File.exists ()) {//if it already exists, delete the old fileFile.delete (); } File=NewFile (FullPath);            File.createnewfile (); //formatting floating-point dataNumberFormat formatter =numberformat.getnumberinstance (); Formatter.setmaximumfractiondigits (10);//set the maximum size of the number of digits to ten//Formatting Date DataSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); //instantiate file output streamFileOutputStream =NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (file), "GB2312"), 1024); //Traverse output per lineiterator<object[]> ite =Rows.iterator ();  while(Ite.hasnext ()) {object[] RowData=(object[]) ite.next ();  for(inti = 0; i < rowdata.length; i++) {Object obj= Rowdata[i];//Current Field//Formatting DataString field = ""; if(NULL!=obj) {                        if(Obj.getclass () = = String.class) {//if it is a stringfield =(String) obj; } Else if(Obj.getclass () = = Double.class|| Obj.getclass () = = Float.class) {//if it is a floating-point typefield = Formatter.format (obj);//format floating-point numbers so that floating-point numbers are not output in scientific notation}Else if(Obj.getclass () = = Integer.class|| Obj.getclass () = = Long.class|| Obj.getclass () = = short.class|| Obj.getclass () = = Byte.class) {//if it's plastic,Field + =obj; } Else if(Obj.getclass () = = Date.class) {//if it is a date typefield =Sdf.format (obj); }                    } Else{field= " ";//give a space placeholder when null                    }                    //stitching all fields with one row of data                    if(I < rowdata.length-1) {//not the last elementFileoutputstream.write ("\" "+ Field +" \ "+", "); } Else{//is the last elementFileoutputstream.write ("\" "+ Field +" \ "")); }                }                //Create a new row                if(Ite.hasnext ()) {fileoutputstream.newline ();        }} fileoutputstream.flush (); } Catch(Exception e) {flag=false; Log.error ("Generated data file is an error!" ", E);        E.printstacktrace (); } finally {            Try{fileoutputstream.close (); } Catch(IOException e) {e.printstacktrace (); }        }        returnFlag; }
View Code

"Service server": Get CSV file contents via restful interface and save as CSV file

1. The "RESTful interface" reads the CSV file generated by the "GB2312" encoding with a stream, where the data stream is encoded as "GB2312".

2. Service server obtains the contents of the CSV file through the "RESTful interface" because the default encoding for service server is "Iso-8859-1". The CSV content encoding received at this time was strongly converted from "GB2312" to "iso-8859-1". In this case, the CSV content that debug sees in eclipse is garbled in Chinese.

3. "Service server" side, re-encode CSV content, so that Chinese characters are no longer garbled.

Content is a string of received CSV content (String type)
Content = Convertencodingformat (content, "iso-8859-1", "GB2312");

4. "Service Server" If you want to save the received CSV file locally, and the Chinese is visible. You also need to set the output stream encoding to "GB2312".

    /*** Write content to file CSV because CSV uses GB2312 encoding and needs to be processed separately*/@SuppressWarnings ("Resource")     Public Static Booleancreatecsvfilewithcontent (String Parentpath, String fileName, String contentstr) {//Mark whether the file was generated successfully        BooleanFlag =true; //stitching file Full pathString FullPath = Parentpath + File.separator +FileName; //file output streamBufferedWriter FileOutputStream =NULL; //generate JSON-formatted files        Try {            //File File =NewFile (FullPath); if(!file.getparentfile (). exists ()) {//If the parent directory does not exist, create a parent directoryfile.getparentfile (). Mkdirs (); }            if(File.exists ()) {//if it already exists, delete the old fileFile.delete (); } File=NewFile (FullPath);            File.createnewfile (); //instantiate file output streamFileOutputStream =NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (file), "GB2312"), 1024);            Fileoutputstream.write (CONTENTSTR);        Fileoutputstream.flush (); } Catch(Exception e) {flag=false; Log.error ("Generated data file is an error!" ", E);        E.printstacktrace (); }        //returns whether the token was successful        returnFlag; }
View Code

This concludes.

Once Java generated CSV file garbled resolution process (GB2312 encoding)

Related Article

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.