在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)
| 归档时间: |
|
| 查看次数: |
2186 次 |
| 最近记录: |