在Delphi中如何读取包含“NULL CHARACTER”的文本文件? [英] How to read a text file that contains 'NULL CHARACTER' in Delphi?
问题描述
我使用 RichEdit1.Lines.LoadFromFile加载文件(FileName,Encoding)
在第一个空字符之后被拖放,并且没有加载剩余的文件。
是否有任何帮助。如何从文本文件中删除NULL Chars。
** BTW我的文本文件编码是UTF8。
阅读该文件不应该是一个问题。相反,当您尝试将数据存储在丰富编辑控件中时,更有可能出现此问题。那些控件不接受任意的二进制数据。您需要确保您只在该控件中放置文本。
将文件加载到普通字符串或流中:
var
s:string;
ss:TStringStream;
s:= TFile.ReadAllText(FileName);
然后删除无效字符。 #0
是Delphi中用于表示空字符的符号。通常,我们可以使用 StringReplace
删除字符:
s:= StringReplace(s,#0,'',[rfReplaceAll]);
然而,它不是二进制安全的;它以空字符停止。相反,您需要一个不同的功能来删除这些字符。 我之前已经展示过。调用该函数调整字符串:
RemoveNullCharacters;
最后,将数据放在rich-edit控件中:
ss:= TStringStream.Create(s);
try
RichEdit1.Lines.LoadFromStream(ss,Encoding);
finally
ss.Free;
结束
I have a text file that contains many NULL CHARACTERS and its encoding is UTF8.
I loaded the file using RichEdit1.Lines.LoadFromFile(FileName,Encoding)
stoped after the first Null Character and it didn't load the rest of file.
Is there any help. How can I remove NULL Chars from a text file.
**BTW My text file encoding is UTF8.
Reading the file shouldn't be a problem. Rather, the problem is more likely when you try to store the data in a rich-edit control. Those controls don't accept arbitrary binary data. You need to ensure you only put text in that control.
Load the file into an ordinary string or stream:
var
s: string;
ss: TStringStream;
s := TFile.ReadAllText(FileName);
Then remove the invalid characters. #0
is the notation in Delphi to represent a null character. Ordinarily, we might use StringReplace
to remove characters:
s := StringReplace(s, #0, '', [rfReplaceAll]);
However, it's not binary-safe; it stops at null characters. Instead, you'll need a different function for removing those characters. I've demonstrated that before. Call that function to adjust the string:
RemoveNullCharacters(s);
Finally, put the data in the rich-edit control:
ss := TStringStream.Create(s);
try
RichEdit1.Lines.LoadFromStream(ss, Encoding);
finally
ss.Free;
end;
这篇关于在Delphi中如何读取包含“NULL CHARACTER”的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!