如果您将其保存到 .txt 文件中,您将无法正确重新加载它,因为您不知道给定换行符最初是嵌入在字符串中还是分隔两个字符串。
如果您将其保存为另一种文本格式,例如.ini,您可以根据需要对换行符进行转义/取消转义,例如:
function Encode(const S: String): String;
begin
Result := StringReplace(S, '<', '<<', [rfReplaceAll]);
Result := StringReplace(Result, #13#10, '<CRLF>', [rfReplaceAll]);
Result := StringReplace(Result, #13, '<CR>', [rfReplaceAll]);
Result := StringReplace(Result, #10, '<LF>', [rfReplaceAll]);
end;
Ini := TIniFile.Create(...);
try
Ini.WriteInteger('section', 'count', MyStringList.Count);
for I := 0 to MyStringList.Count-1 do
Ini.WriteString('section', IntToStr(I), Encode(MyStringList[I]);
finally
Ini.Free;
end;
function Decode(const S: String): String;
begin
Result := StringReplace(S, '<LF>', #10, [rfReplaceAll]);
Result := StringReplace(Result, '<CR>', #13, [rfReplaceAll]);
Result := StringReplace(Result, '<CRLF>', #13#10, [rfReplaceAll]);
Result := StringReplace(Result, '<<', '<', [rfReplaceAll]);
结束;
Ini := TIniFile.Create(...);
try
Count := Ini.ReadInteger('section', 'count', 0);
for I := 0 to Count-1 do
MyStringList.Add(Decode(Ini.ReadString('section', IntToStr(I), ''));
finally
Ini.Free;
end;
如果将其保存为二进制格式,则可以按原样保留换行符,例如:
procedure WriteIntegerToStream(Stream: TStream; Value: Integer);
begin
Stream.WriteBuffer(Value, SizeOf(Integer));
end;
procedure WriteStringToStream(Stream: TStream; const Value: String);
var
U: UTF8String;
Count: Integer;
begin
U := UTF8String(Value); // or UTF8Encode(Value) prior to D2009
Count := Length(U);
WriteIntegerToStream(Stream, Count);
if Count > 0 then
Stream.WriteBuffer(PAnsiChar(U)^, Count * SizeOf(AnsiChar));
end;
Strm := TFileStream.Create(..., fmCreate);
try
WriteIntegerToStream(Stream, MyStringList.Count);
for I := 0 to MyStringList.Count-1 do
WriteStringToStream(Stream, MyStringList[I]);
finally
Stream.Free;
end;
function ReadIntegerFromStream(Stream: TStream): Integer;
begin
Stream.ReadBuffer(Result, SizeOf(Integer));
end;
function ReadStringFromStream(Stream: TStream): String;
var
Count: Integer;
U: UTF8String;
begin
Count := ReadIntegerFromStream(Stream);
if Count > 0 then
begin
SetLength(U, Count);
Stream.ReadBuffer(PAnsiChar(U)^, Count * SizeOf(AnsiChar));
Result := String(U); // or UTF8Decode(U) prior to D2009
end else
Result := '';
end;
Stream := TFileStream.Create(..., fmOpenRead or fmShareDenyWrite);
try
Count := ReadIntegerFromStream(Stream);
for I := 0 to Count-1 do
MyStringList.Add(ReadStringFromStream(Stream));
finally
Stream.Free;
end;