开发者

How to make Delphi and Android use the same charset?

开发者 https://www.devze.com 2023-03-31 06:03 出处:网络
I\'m doing a project for anwsering questionnaires. The user creates the project with the questions on Delphi, than exports the project in a .txt file to Android, where the file is read and the user ca

I'm doing a project for anwsering questionnaires. The user creates the project with the questions on Delphi, than exports the project in a .txt file to Android, where the file is read and the user can answer. My problem is in characters like á,à,É,Ú, that appear like a ? in An开发者_StackOverflow中文版droid, with the code 65533. So, I need to know how to configure Android and Delphi to work in the same charset.


Android is Linux based and so presumably uses UTF-8. On the other hand, Android is also very Java-like and so possibly prefers UTF-16.


If you need the file to be UTF-8, you can do it like this, assuming you have your text in a TStringList.

StringList.SaveToFile(FileName, TEncoding.UTF8);

This will include a BOM in the file which I imagine Android won't like—Windows UTF-8 apps tend to use BOMs, but not Linux. If you want to output without a BOM do it like this:

type
  TUTF8EncodingNoBOM = class(TUTF8Encoding)  
  public
    function GetPreamble: TBytes; override;
  end;

function TUTF8EncodingNoBOM.GetPreamble: TBytes;
begin
  Result := nil;
end;
...
var
  UTF8EncodingNoBOM: TEncoding;//make this a global variable
...
UTF8EncodingNoBOM := TUTF8EncodingNoBOM.Create;//create in a unit initialization, remember to free it
...
StringList.SaveToFile(FileName, UTF8EncodingNoBOM);

If you discover you need UTF-16 then use TEncoding.Unicode for UTF-16LE or TEncoding.BigEndianUnicode for UTF-16BE. If you need to strip the BOM then that's easy enough with the same technique as above.

Summary

  1. Work out what encoding you need, and its endianness.
  2. Find an appropriate TEncoding.
  3. Use TStrings.SaveToFile with that TEncoding instance.


Use Unicode. UTF-16 or UTF-8 should work fine.

See Davids answer for an explanation why this should work and how to do it in D2009 and newer.

For Delphi 2007 and older you have to use another solution, UTF8Encode + Ansi TStringList can be used, you can also convert your strings to WideStrings and use WideStrings.

To write UTF-8 using D2007 and older see this question:

How can a text file be converted from ANSI to UTF-8 with Delphi 7?

To write UTF-16 using D2007 you can use the WideStrings unit which contains a TWideStringList. Beware that this class doesn't write the BOM by default.

There are also other WideStringList implementations for older Delphi versions out there.

0

精彩评论

暂无评论...
验证码 换一张
取 消