简体   繁体   中英

Error while writing to external storage Android studio

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?

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 aka 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM