Mit folgenden Funktionen kann man Dateien im
UTF-16 Format laden und speichern.
Delphi-Quellcode:
// Hilfsfunktion zum vertauschen der Byteorder in einem WideString
procedure SwapWideString(var ws:WideString);
var
i : Integer;
begin
for i := 1 to length(ws) do
ws[i] := WideChar(Swap(Ord(ws[i])));
end;
procedure SaveWideStringToFile(const filename:string; const ws:WideString);
var
fs : TFileStream;
data : WideString;
begin
data := ' '+ws;
data[1] := Widechar($FEFF); // BOM = Byte Order Mark
// SwapWideString(data);
fs := TFileStream.Create(filename, fmCreate);
try
fs.WriteBuffer(data[1], Length(data)*sizeof(Widechar));
finally
fs.Free;
end;
end;
function LoadWideStringFromFile(const filename:string):WideString;
var
fs : TFileStream;
bom : WideChar;
begin
fs := TFileStream.Create(filename, fmOpenRead and fmShareDenyWrite);
try
fs.ReadBuffer(bom, sizeof(bom));
SetLength(Result, (fs.Size div sizeof(widechar))-1);
fs.ReadBuffer(Result[1], fs.Size-sizeof(bom));
if bom = Widechar($FEFF) then
else if bom = Widechar($FFFE) then
SwapWideString(Result)
else
raise EConvertError.Create('unsupported Byte Order Mark in file '+filename);
finally
fs.Free;
end;
end;