14

How can I save a file locally on an Android device, using Delphi (XE5, Firemonkey)?

Something as simple as

  Memo.Lines.SaveToFile('test.txt')

does not seem to work. It results in the following error message:

"Cannot create file "/test.txt". Not a directory."

3
  • When you say locally, what do you mean? SDCard (internal/external?), private data? Other? You cannot create a file in / without root and permissions.
    – Simon
    Sep 17, 2013 at 19:22
  • I was hoping that I could just write in the 'current directory' of the internal storage (whereever that may be). Note that I didn't specify the backslash before the file name. I am surprised that it seems to try to write in the root.
    – Reinier
    Sep 17, 2013 at 19:24
  • I also tried this path: "/Android/data/com.embarcadero.TestLocalStorage/files/" (developer.android.com/guide/topics/data/data-storage.html seems to indicate that that may be a proper location for Internal Storage). But got the same result
    – Reinier
    Sep 17, 2013 at 19:27

4 Answers 4

19

According to the document Creating an Android App, get the documents path like this:

System.IOUtils.TPath.GetDocumentsPath + System.SysUtils.PathDelim + 'myfile';
2
  • That's what I was looking for. Thanks a lot! BTW: in this case: no specific permissions are necessary.
    – Reinier
    Sep 17, 2013 at 19:47
  • 13
    Don't you want to use Path.Combine or whatever the function is Sep 17, 2013 at 20:00
11

Instead of using System.SysUtils.PathDelim, you may use

System.IOUtils.TPath.Combine(System.IOUtils.tpath.getdocumentspath,'test.txt');

Combine chooses between the windows \ and the Linux /

System.IOUtils must be used in this line instead of setup in the uses clause because there are probably more Tpath initials.

2

GetHomePath, return a string with the path. -> 'data/data//files'

You can to use:

Memo.Lines.SaveToFile(format('%s/test.txt', [GetHomePath]));

Or this form

Memo.Lines.SaveToFile(GetHomePath + '/test.txt');
2

on my device (and presumably all android devices?) GetHomePath incorrectly gives me /storage/emulated/0/... whereas I need /storage/sdcard0/... to get to the storage visible in Windows Explorer via USB.

so the full path to my files may be '/storage/sdcard0/Android/data/com.embarcadero.(my app name)/files/'

Presumably if you have a plug in SD card this might be sdcard1 or whatever.

You can list the contents of your device storage folder with code like this

  P := '/storage/';
  if (FindFirst(P + '*', faAnyFile, Sr) = 0) then
  repeat
    Memo1.Lines.Add(Sr.Name);
  until (FindNext(Sr) <> 0);
  FindClose(Sr);

On my device this gives me:

sdcard0 usb emulated

then change S when you want to explore subfolders

Note that the files folder gets emptied each time you recompile and deploy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.