1. package main
    2. import (
    3. "bufio"
    4. "fmt"
    5. "log"
    6. "os"
    7. "golang.org/x/text/encoding/simplifiedchinese"
    8. "golang.org/x/text/transform"
    9. )
    10. // Encoding to use. Since this implements the encoding.Encoding
    11. // interface from golang.org/x/text/encoding you can trivially
    12. // change this out for any of the other implemented encoders,
    13. // e.g. `traditionalchinese.Big5`, `charmap.Windows1252`,
    14. // `korean.EUCKR`, etc.
    15. var enc = simplifiedchinese.GBK
    16. func main() {
    17. const filename = "example_GBK_file"
    18. exampleWriteGBK(filename)
    19. exampleReadGBK(filename)
    20. }
    21. func exampleReadGBK(filename string) {
    22. // Read UTF-8 from a GBK encoded file.
    23. f, err := os.Open(filename)
    24. if err != nil {
    25. log.Fatal(err)
    26. }
    27. r := transform.NewReader(f, enc.NewDecoder())
    28. // Read converted UTF-8 from `r` as needed.
    29. // As an example we'll read line-by-line showing what was read:
    30. sc := bufio.NewScanner(r)
    31. for sc.Scan() {
    32. fmt.Printf("Read line: %s\n", sc.Bytes())
    33. }
    34. if err = sc.Err(); err != nil {
    35. log.Fatal(err)
    36. }
    37. if err = f.Close(); err != nil {
    38. log.Fatal(err)
    39. }
    40. }
    41. func exampleWriteGBK(filename string) {
    42. // Write UTF-8 to a GBK encoded file.
    43. f, err := os.Create(filename)
    44. if err != nil {
    45. log.Fatal(err)
    46. }
    47. w := transform.NewWriter(f, enc.NewEncoder())
    48. // Write UTF-8 to `w` as desired.
    49. // As an example we'll write some text from the Wikipedia
    50. // GBK page that includes Chinese.
    51. _, err = fmt.Fprintln(w,
    52. `In 1995, China National Information Technology Standardization
    53. Technical Committee set down the Chinese Internal Code Specification
    54. (Chinese: 汉字内码扩展规范(GBK); pinyin: Hànzì Nèimǎ
    55. Kuòzhǎn Guīfàn (GBK)), Version 1.0, known as GBK 1.0, which is a
    56. slight extension of Codepage 936. The newly added 95 characters were not
    57. found in GB 13000.1-1993, and were provisionally assigned Unicode PUA
    58. code points.`)
    59. if err != nil {
    60. log.Fatal(err)
    61. }
    62. if err = f.Close(); err != nil {
    63. log.Fatal(err)
    64. }
    65. }