There are two types of file storage areas for Android devices:
internal storage and external storage ("internal" and "external" storage). The name comes from early Android, when most Android devices offer two ways of storage: Built-in nonvolatile memory (internal storage) and removable Storage such as micro SD cards (external storage). Some devices divide permanent memory into internal and external parts, so there are still two storage spaces, even without external storage. The API's approach is the same regardless of whether there is external storage.
Internal Storage:
- It's always available.
- Saved files can only be accessed by your app in the default way
- Uninstall the app, and the system removes all files from your app from the internal storage
Internal storage is available for users or other apps that you don't want to access your files
External storage:
- Not always available (users may connect external storage as USB and, in some cases, remove it from the device)
- is globally readable (world-readable), so some files may be read in an uncontrolled manner
- Uninstall the app and delete only the data you stored in
getExternalFilesDir()目录下的文件
外部存储适用于不需要存储限制的文件以及你想要与其他app共享的文件或者是允许用户用电脑访问的文件
app默认安装在内部存储中,通过指定android:installLocation
属性值可以让app安装在外部存储中。
获取外部存储权限:
Read and write:
< ... > < android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> ... </ Manifest >
Read:
< ... > < android:name= "Android.permission.READ_EXTERNAL_STORAGE"/> ... </manifest>
You do not need any permissions to save files in the internal store, and your app always has read and write permissions in the internal storage.
To save the file in the internal store:
Get the appropriate directory:
Getfilesdir () directory of the app files in internal storage
eg
New File (Context.getfilesdir (), filename);
Getcachedir () app temporary cache file directory in internal storage
Call Openfileoutput () get FileOutputStream write file to internal directory
eg
1String filename = "MyFile";2String string = "Hello world!";3 FileOutputStream OutputStream;4 5 Try {6OutputStream =openfileoutput (filename, context.mode_private);7 Outputstream.write (String.getbytes ());8 outputstream.close ();9}Catch(Exception e) {Ten e.printstacktrace (); One}
createTempFile()
Cache Some files:
1 PublicFile GetTempFile (context context, String URL) {2 file file;3 Try {4String FileName =uri.parse (URL). getlastpathsegment ();5File = File.createtempfile (FileName,NULL, Context.getcachedir ());6 Catch(IOException e) {7 //Error while creating file8 }9 returnfile;Ten}
Android Learning Note-save file (saving files)