问题
Currently, I'm using below method to create a path in android external storage.
public void createPath() {
String path = Environment.getExternalStorageDirectory().getPath()+"/myFolder/";
boolean exists = (new File(path)).exists();
if (!exists) {
new File(path).mkdirs();
}
}
As far as I understand getExternalStorageDirectory()
does not exclusively refer to external storage. So this method will create myFolder
in user preferred storage (which is generally internal storage).
Now I have a question:
What happens if the default storage(user preferred storage) has been set to SD Card
and it's not readable/writable? What is the best way to handle this situation?
In another word, How can I create this folder safely?(Internal or External doesn't matter ).
回答1:
create folder in internal storage is safe and No need to access.
//Get free Size internal memory
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
long freeSizeInternalMemoryMB = ((availableBlocks * blockSize) / 1024) / 1024;
//2M available
if (freeSizeInternalMemoryMB > 2) {
//code for create and copy file
}else{
//show error for low storage
}
回答2:
As far as I understand getExternalStorageDirectory() does not exclusively refer to external storage.
Yes, it does, for what the Android SDK refers to as external storage.
So this method will create myFolder in user preferred storage (which is generally internal storage).
No, what the Android SDK refers to as internal storage is something else.
What happens if the default storage(user preferred storage) has been set to SD Card and it's not readable/writable?
Android itself does not have a concept of "user preferred storage", unless I am misinterpreting your description.
How can I create this folder safely?
Your code there seems fine.
There is a very small percentage of devices (my guess: ~0.1%) where external storage is on removable media. This was the dominant model for Android 1.x/2.x, but those devices are not used much anymore, and most newer devices have internal and external storage both on on-board flash. If the user ejected the removable media, you will not have access to external storage. There are methods on Environment
for getting the external storage state. However, you then have no place to write your files where the user can access them. Your choices would be:
Store the files on internal storage, then migrate them to external storage at a later time, when the media is available again
Do not store anything, asking the user to please make external storage available again
来源:https://stackoverflow.com/questions/45128244/how-to-write-read-a-folder-file-in-android-storage