Save TList objects in a text file

I have the following classes:

type TSong = class(TObject) private FArtist: String; FTitle: String; procedure SetArtist(Artist: String); procedure SetTitle(Title: String); public property Artist: String read FArtist Write SetArtist; property Title: String read FTitle Write SetTitle; constructor Create(Artist, Title: String); end; type TPlaylist = class(TList) private procedure ShowInListBox(Box: Pointer); public { Public-Deklarationen } end; 

At runtime, I instantiate these classes:

 Playlist := TPlaylist.Create; Playlist.Add(TSong.Create('Artist 1', 'Title 1')); Playlist.Add(TSong.Create('Artist 2', 'Title 2')); Playlist.Add(TSong.Create('Artist 3', 'Title 3')); Playlist.Add(TSong.Create('Artist 4', 'Title 4')); 

When the program is closed, I would like to save this data to a text file. How can i do this?

The best way would probably be to create a procedure related to the TPlaylist class, right?

 procedure SaveToTxtFile(fName: String); 

What should such a function do? When the program starts again, I would like to create a playlist again.

It would be nice if the data were saved in a text file as follows:

 Artist 1///Title 1 Artist 2///Title 2 
+4
source share
1 answer

You are on the right way. What you are trying to do is called serialization, turning the object into a smooth shape, such as a file.

You need to develop a format. Exactly what format does not matter if it is consistent and saves all the data needed to restore the object. You say you want a text file, so in this case you can make several shortcuts using the TStringList into which the IO file is embedded.

Try something like this:

 procedure TSong.Serialize(serializer: TStringList); begin serializer.Add(format('%s///%s: %s', [Artist, Title, Filename])); //add a filename member! You need one! end; procedure TPlaylist.Serialize(const filename: string); var serializer: TStringList; i: integer; begin serializer := TStringList.Create; try for i := 0 to Count - 1 do TSong(self[i]).Serialize(serializer); serializer.SaveToFile(filename); finally serializer.Free; end; end; 

You will also want to implement inversion, deserialization. It should not be too complicated.

+7
source

Source: https://habr.com/ru/post/1301271/


All Articles