如何读取文件,如果UTF-8无效,则中止错误?

ke.*_*ke. 5 go

在Go中,我想逐行读入一个文件,进入str's或者[]runes.

该文件应以UTF-8编码,但我的程序不应该信任它.如果它包含无效的UTF-8,我想正确处理错误.

bytes.Runes(s []byte) []rune,但没有错误返回值.遇到无效的UTF-8会不会感到恐慌?

pet*_*rSO 10

例如,

package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "os"
    "strings"
    "unicode/utf8"
)

func main() {
    tFile := "text.txt"
    t := []byte{'\xFF', '\n'}
    ioutil.WriteFile(tFile, t, 0666)
    f, err := os.Open(tFile)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer f.Close()
    r := bufio.NewReader(f)
    s, err := r.ReadString('\n')
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    s = strings.TrimRight(s, "\n")
    fmt.Println(t, s, []byte(s))
    if !utf8.ValidString(s) {
        fmt.Println("!utf8.ValidString")
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

[255 10] ? [255]
!utf8.ValidString
Run Code Online (Sandbox Code Playgroud)

  • 总结一下:1.将输入读入[]字节或字符串2.使用utf8.Valid或utf8.ValidString检查是否有效3.如果有效,如果需要使用bytes.Runes或[] rune(str)转换为[]符文谢谢!我选择这个答案是因为写一个循环来完成输入 - 就像在jnml的例子中 - 并不是每次出现这个问题时我想做的事情. (2认同)