Lenguaje de programación Borland Delphi
Mostramos a continuación un ejemplo de procedimiento Delphi que convierte un texto pasado como parámetro a UTF-8 con BOM (Byte Order Mark o Marca de orden de bytes) y lo guarda en fichero.
procedure generarFicheroUTF8conBOM (archivo : String; texto : string);
const
cUTF8 = $BFBBEF; //hexadecimal para BOM
var
textoUTF8 : UTF8String;
ficheroSalida : TFileStream;
valorBOM : Integer;
begin
if (Trim(texto) <> ') then
begin
textoUTF8 := UTF8Encode (texto);
ficheroSalida := Tfilestream.create(archivo, fmCreate);
try
valorBOM := cUTF8;
//insertar marca BOM al principio del fichero
ficheroSalida.WriteBuffer(valorBOM, sizeof(valorBOM) - 1);
//guardamos fichero con resto del texto
ficheroSalida.WriteBuffer(textoUTF8[1], Length(textoUTF8) * Sizeof(textoUTF8[1]));
finally
ficheroSalida.free
end;
end;
end;
Un ejemplo de uso:
var
cadena : string;
begin
cadena := '<?xml version="1.0" encoding="utf-8"?><factura></factura>';
generarFicheroUTF8conBOM'C:\facturas\facturas.xml, cadena);
MessageDlg('Fichero de factuas XML generado correctamente convertido a UTF-8 con BOM.' ,
mtInformation, [mbok], 0);
end;
Publicado el: 2014-05-15