0

I am trying to create a file, but something is wrong with the pathname. The writing permissions are declared in the manifest. I specify the pathname below:

String path =  ":/storage/sdcard0/";

and then try to access that later:

try {
        File file = new File(path + "ratings.csv");
        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

And this throws IOException: "No such file or directory". Is the pathname wrong?

OttoIEM
  • 21
  • 4

1 Answers1

1

Yup, the path is precisely wrong and you are not supposed to add a ':' at the beginning.

(Maybe you just got used to Windows)

I suggest to NEVER, (I mean it) NEVER hard-code file paths.

But why?

That's because you are incredibly making your code susceptible to IOExceptions.

You are also removing the compatibility layer for other devices that support the Android VM on top of their underlying OS (like Chromebooks a.k.a. Chrome OS, customized versions, etc.) .

I suggest reading this answer that belongs on SO as well if you really need to write to an sdcard.


TL;DR

Path name wrong, hard-code path evil, ooga booga.

JumperBot_
  • 551
  • 1
  • 6
  • 19
  • `I suggest to NEVER` call getExternalStorageState() and never check for mounted as external storage is always available. – blackapps Jul 30 '22 at 08:57
  • `// Store data in file under sdcard/Downloads/` You mean under `/storage/emulated/0/Downloads`. – blackapps Jul 30 '22 at 08:58
  • Why do you make all `final`? – blackapps Jul 30 '22 at 08:59
  • @blackapps I'll answer it one by one. The OP wants it under the external storage (the sdcard). I unconsciously set it all to final for some reason. – JumperBot_ Jul 30 '22 at 09:02
  • The 'external storage' is not a removable micro-sd-card. Its just internal memory that is always available. A confusing historical naming. – blackapps Jul 30 '22 at 09:04
  • `suggest reading this tutorial if you really need to write to an sdcard.` Sorry that does not write to a removable micro sd card either. Moreover its code form a hundred years ago.. – blackapps Jul 30 '22 at 09:07
  • @blackapps I understand, it did came from the documentation in the first place. Also, yes it is old and I did find a better link (being edited atm). – JumperBot_ Jul 30 '22 at 09:09