Golang reading file encoding conversion problem

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

First import the Package

"Code.google.com/p/mahonia"

This package can be obtained through this link

https://code.google.com/p/mahonia/

The reference code is as follows:

package mainimport  (     "Bufio"      "code.google.com/p/ Mahonia "    " Log "    " OS "    " strings "      "Time") Func main ()  {    //Create the log file     t :=  time. Now ()     filepath :=  "./log_"  + strings. Replace (t.string () [:19],  ":",  "_",  3)  +  ". txt"     file, err  := os. OpenFile (Filepath, os. o_create, 0666)     if err != nil {         log. Fatal ("create log file failed!")     }    defer file. Close ()     wfile := bufio. Newwriter (file)     wfile.writestring (ReadFile ())     wfile.flush ()}func  readfile ()  striNg {    f, err := os. Open ("Ex7.txt")     if err != nil {         return err. Error ()     }    defer f.close ()     buf : = make ([]byte, 1024)     //file ex7.txt encoding is Gb18030    decoder  := mahonia. Newdecoder ("GB18030")     if decoder == nil {         return  "Code does not exist!"     }    var str string =  ""      for {        n, _ := f.read (BUF)          if 0 == n {             break        }        //decoding to Utf-8        str  += decoder. Convertstring (String (Buf[:n]))     }    return str}


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.