问题
I know how to read a file with Haxe by using sys.io.File.read (compare Reading lines from a file in Haxe and I also know that the sys module is not available for each target). However how can I tell sys.io.File.read that my text file is encoded via a certain encoding (e.g. UTF-16, UTF-8, ISO-8859-1, ...)?
回答1:
There is no way to do this at File
-level, but you can encode / decode the String
after reading the file. For instance, Utf8.encode() will convert a ISO-8859-1 string to a UTF-8 string:
var isoString = sys.io.File.getContent("iso_file.txt");
var utf8String = haxe.Utf8.encode(isoString);
sys.io.File.saveContent("utf8_file.txt", utf8String);
The standard library currently doesn't support UTF-16, but it's coming in Haxe 4. In the meantime, you can use libraries such as unifill for that.
Btw, if you don't need to read a file line-by-line, File.getContent() is much more convenient than the File.read()
-approach you linked.
来源:https://stackoverflow.com/questions/48679934/specifing-file-encoding-while-reading-a-file-with-sys-io-file-read-in-haxe