Android: write on external storage using getExternalStoragePublicDirectory(String type)

a 夏天 提交于 2019-12-11 07:45:15

问题


So I would like to save some data on external storage on android. And I have looked at the the api where is says getExternalStoragePublicDirectory(String type) "This method will create the appropriate directory if necessary." These are the default directories: Music,Podcasts,Ringtones,Alarms,Notifications,Pictures,Movies,Download. So my question is:

  1. How do I create a new directory of my own?
  2. How can I make it invisible to the user? so that user will not get frustrated with the extra folder.

回答1:


You can use coder_For_Life22's answer about creating the folders, and then to make it "more-invisible" to the users, you can do the following:

  1. Name it starting with dot. e.g. ".yourappname"
  2. Put an empty file ".nomedia" into your folder. This prevents the media scanner from recording the files you have on that folder.



回答2:


You could do something like this, get your application directory

String pathToExternalStorage = Environment.getExternalStorageDirectory().toString();
File appDirectory = new File(pathToExternalStorage + "/" + "AppName");   
// have the object build the directory structure, if needed.
appDirectory.mkdirs();

Now this creates a custom directory on external storage as the android docs says..

If you want to save files that are not specific to your application and that should not be deleted when your application is uninstalled, save them to one of the public directories on the external storage. These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and others.

EDIT:

Use Context.getDir(String name, int mode) method to create or access directories in internal storage. Quote from docs:

Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.

Example:

File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir, set it to private so its only visible to our application;


来源:https://stackoverflow.com/questions/8888451/android-write-on-external-storage-using-getexternalstoragepublicdirectorystrin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!