【问题标题】:Delphi 6 convert ucs-2 little endian file to utf8Delphi 6 将 ucs-2 little endian 文件转换为 utf8
【发布时间】:2016-03-10 08:21:52
【问题描述】:

我正在尝试导入具有 ucs2 little endian 编码的 csv 文件。我正在使用绝地组件(jvCsvDataset)来收集和处理数据。该组件无法使用此编码读取数据,我需要将其转换为 utf8。问题是我需要在 delphi 6 中完成。

您知道“ucs2decode”函数或任何其他方法吗?

提前致谢!

【问题讨论】:

  • 使用 WideCharToMultiByte

标签: delphi encoding delphi-6


【解决方案1】:

读取WideString中的文件,然后使用UTF8Encode,可能是这样的:

function ReadUCS2FileToUTF8(const FilePath: string): UTF8String;
var
  f: TFileStream;
  d: WideString;
begin
  f := TFileStream.Create(FilePath, fmOpenRead or fmShareDenyWrite);
  try
    SetLength(d, f.Size div SizeOf(WideChar));
    if Length(d) > 0 then
      f.ReadBuffer(d[1], Length(d) * SizeOf(WideChar));
  finally
    f.Free;
  end;
  Result := UTF8Encode(d);
end;

【讨论】:

  • 请注意,Delphi 6 中的UTF8Encode()UTF8Decode() 是不完整的。他们手动实现 UTF-8,并且只处理最多 3 个字节的 UTF-8 字节序列(Unicode 代码点 U-0000U+FFFF,但不是更高)。因此,要处理更高的代码点,您将不得不直接使用 WideCharToMultiByte()MultiByteToWideChar()UTF8Encode()UTF8Decode() 在以后的 Delphi 版本中进行了更新以供使用)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-09
  • 2013-06-09
  • 2022-06-10
  • 1970-01-01
  • 2017-08-26
  • 2014-04-18
相关资源
最近更新 更多