UTF-16 テキスト ファイルをバイトに読み取る場合標準入力メソッドを使用して配列を使用すると、ファイルの UTF-16 エンコード文字が正しく解釈されない可能性があります。これにより、バイトが ASCII として扱われ、文字列表現が正しくなくなる可能性があります。
UTF-16 テキスト ファイルを適切に読み取るには、次を使用することが重要です。 UTF-16 エンコーディングを処理するために特別に設計されたメソッド。 golang.org/x/text/encoding/unicode パッケージは、この目的に必要な機能を提供します。
func ReadFileUTF16(filename string) ([]byte, error) { // Read the file into a byte array raw, err := ioutil.ReadFile(filename) if err != nil { return nil, err } // Create a transformer that converts MS-Windows default to UTF8 win16be := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) // Override the BOM to ensure it is respected utf16bom := unicode.BOMOverride(win16be.NewDecoder()) // Apply the transformer to the input byte array unicodeReader := transform.NewReader(bytes.NewReader(raw), utf16bom) // Decode the data into a new byte array decoded, err := ioutil.ReadAll(unicodeReader) return decoded, err }
ファイル全体を読み取ることが不可能なシナリオの場合、次の関数は同じ UTF-16 デコードを使用するスキャナーを作成します。ロジック:
func NewScannerUTF16(filename string) (utfScanner, error) { // Read the file into a []byte file, err := os.Open(filename) if err != nil { return nil, err } // Create a transformer that converts MS-Windows default to UTF8 win16be := unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM) // Override the BOM to ensure it is respected utf16bom := unicode.BOMOverride(win16be.NewDecoder()) // Apply the transformer to the input file unicodeReader := transform.NewReader(file, utf16bom) return unicodeReader, nil }
golang.org/x/text/encoding/unicode パッケージは、バイト オーダー マーク (BOM) をインテリジェントに解釈して、使用されるエンコーディングを決定します。ファイル。ただし、bufio パッケージの ReadLine 関数は Unicode デコードをサポートしていないことに注意することが重要です。
UTF-16 デコードに関連する追加のカスタマイズとオプションについては、オープン ソースを参照してください。モジュール (https://github.com/TomOnTime/utfutil/.
)以上がGo で UTF-16 テキスト ファイルを文字列として正しく読み取るにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。