在 Haxe 中使用 sys.io.File.read 读取文件时指定文件编码

Specifing file encoding while reading a file with sys.io.File.read in Haxe

我知道如何使用 sys.io.File.read 使用 Haxe 读取文件(比较 Reading lines from a file in Haxe 我也知道 sys 模块不适用于每个目标)。但是,我如何告诉 sys.io.File.read 我的文本文件是通过某种编码(例如 UTF-16、UTF-8、ISO-8859-1 等)编码的?

无法在 File 级别执行此操作,但您可以在读取文件后对 String 进行编码/解码。例如,Utf8.encode() 会将 ISO-8859-1 字符串转换为 UTF-8 字符串:

var isoString = sys.io.File.getContent("iso_file.txt");
var utf8String = haxe.Utf8.encode(isoString);
sys.io.File.saveContent("utf8_file.txt", utf8String);

标准库目前不支持 UTF-16,但 it's coming in Haxe 4. In the meantime, you can use libraries such as unifill 支持。

顺便说一句,如果您不需要逐行读取文件,File.getContent() 比您链接的 File.read() 方法方便得多。