如何使用Delphi XE的TEncoding将西里尔文或ShiftJis文本保存到文件?
我正在尝试使用 Delphi XE 将与我的系统不同的代码页(例如西里尔字母)中的一些文本行保存到 TFileStream。但是我找不到任何代码示例来生成这些编码文件?
我尝试使用与 TStrings.SaveToStream 相同的代码,但是我不确定我是否正确实现了它(例如 WriteBom 部分),并且想知道它在其他地方是如何完成的。这是我的代码:
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;
提前致谢。
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 ?
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;
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定您在寻找什么示例;以下内容可能会有所帮助 - 该示例将 unicode 字符串 (SL) 转换为 ANSI 西里尔字母:
Not sure what example are you looking for; may be the following can help - the example converts unicode strings (SL) to ANSI Cyrillic:
如果我理解的话就很简单了。声明一个与 Cyrillic 1251 相似的 AnsiString:
然后将您的 Unicode 字符串分配给以下之一:
然后您可以以传统方式将
CyrillicText
写入流:ANSI 编码的文本文件不应有 BOM 。
If I understand it's pretty simple. Declare an AnsiString with affinity for Cyrillic 1251:
Then assign your Unicode string to one of these:
You can then write
CyrillicText
to a stream in the traditional manner:There should be no BOM for an ANSI encoded text file.