Home » Android » android – Saving data on external storage

android – Saving data on external storage

Posted by: admin June 15, 2020 Leave a comment

Questions:

I want to save some data in the user’s external directory (ie. SD card), but there seems to be a weird problem. I’m using Environment.getExternalStorageDirectory() which returns “mnt/sdcard/” (which is fine). I want to create two folders on in this directory so I do:

File main = new File(getExternalStorageDirectory() + "/my_app/some_data");
if(!main.isDirectory())
    main.mkdirs();

Now I thought this would make the directory “mnt/sdcard/my_app/some_data”, but after using a file manager to look at the SD card, it turns out that this folder is created at “mnt/sdcard/my_app/mnt/sdcard/my_app/some_data”, which is quite bizarre. Can anyone tell me how to fix this?

How to&Answers:

Try the following and see what you get…

String packageName =  this.getPackageName();
File myFilesDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator  + "Android" + File.separator + "data" + File.separator + packageName + File.separator + "files");
myFilesDir.mkdirs();

It’s exacly what I use to create a working directory on an SD card. For me it creates…

/mnt/sdcard/Android/data/com.mycompany.myApp/files

…where ‘com.mycompany.myApp’ is the actual package name of my app.