如何使用Delphi XE的TEncoding将西里尔字母或ShiftJis文本保存到文件中? [英] How to use Delphi XE's TEncoding to save Cyrillic or ShiftJis text to a file?

查看:213
本文介绍了如何使用Delphi XE的TEncoding将西里尔字母或ShiftJis文本保存到文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Delphi XE将与系统不同的代码行中的某些文本行(例如西里尔字母)保存到TFileStream中。但是我找不到任何代码示例来生成这些编码文件?

I'm trying to save some lines of text in a codepage different from my system's such as Cyrillic to a TFileStream using Delphi XE. However I can't find any code sample to produce those encoded file ?

我尝试使用与TStrings.SaveToStream相同的代码,但是我不确定我是否正确实现了它(例如WriteBom部分),并且想知道如何在其他地方完成。这是我的代码:

I tried using the same code as TStrings.SaveToStream however I'm not sure I implemented it correctly (the WriteBom part for example) and would like to know how it would be done elsewhere. Here is my code:

FEncoding := TEncoding.GetEncoding(1251);
FFilePool := TObjectDictionary<string,TFileStream>.Create([doOwnsValues]);

//...

procedure WriteToFile(const aFile, aText: string);
var
  Preamble, Buffer: TBytes;
begin
  // Create the file if it doesn't exist
  if not FFilePool.ContainsKey(aFile) then
  begin
    // Create the file
    FFilePool.Add(aFile, TFileStream.Create(aFile, fmCreate));
    // Write the BOM
    Preamble := FEncoding.GetPreamble;
    if Length(Preamble) > 0 then
     FFilePool[aFile].WriteBuffer(Preamble[0], Length(Preamble));
  end;
  // Write to the file
  Buffer := FEncoding.GetBytes(aText);
  FFilePool[aFile].WriteBuffer(Buffer[0], Length(Buffer));
end;

预先感谢。

推荐答案

如果我理解这很简单。声明一个对西里尔字母1251具有亲和力的AnsiString:

If I understand it's pretty simple. Declare an AnsiString with affinity for Cyrillic 1251:

type
  // The code page for ANSI-Cyrillic is 1251
  CyrillicString = type AnsiString(1251);

然后将您的Unicode字符串分配给以下之一:

Then assign your Unicode string to one of these:

var
  UnicodeText: string;
  CyrillicText: CyrillicString;
....
  CyrillicText := UnicodeText;

然后可以将 CyrillicText 写入流中以传统方式:

You can then write CyrillicText to a stream in the traditional manner:

if Length(CyrillicText)>0 then
  Stream.WriteBuffer(CyrillicText[1], Length(CyrillicText));

ANSI编码的文本文件应该没有BOM。

There should be no BOM for an ANSI encoded text file.

这篇关于如何使用Delphi XE的TEncoding将西里尔字母或ShiftJis文本保存到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆