Search code examples
androiddelphifiremonkey

Write some text and save on my android phone


I'm trying to save some text on file (test.txt) on my android phone but unsuccessful. This is my code example:

procedure TDM.WriteLog(text:string);
var
   myFile : TextFile;


 begin


   // Try to open the Test.txt file for writing to
   AssignFile(myFile, System.IOUtils.TPath.Combine(System.IOUtils.tpath.getdocumentspath,'test.txt'));
   ReWrite(myFile);

   // Write a couple of well known words to this file
   WriteLn(myFile, text + sLineBreak );


   // Close the file
   CloseFile(myFile);


 end;

When i locate file on my phone i open file but it is empty. What I missed?


Solution

  • When you want to create a text file in Android (it's the same with iOS and macOS of course) you can use the WriteAllText class procedure that belongs to the TFile class. You have to add in the uses clause System.IOUtils.

    TFile.WriteAllText(TPath.Combine(TPath.GetDocumentsPath, 'test.txt'), 'content');
    

    When you want to store a text file, or in general data related to your app, it's recommended that you use the GetDocumentsPath. This is a modern way to create a text file but it's not the only one; consider also that you could:

    1. Use a TStringlist and then call SaveToFile('path')
    2. If you are using a memo it has the SaveToFile('path') function
    3. Use the TStreamWriter class (and the StreamReader to read the content)