问题
Everything is in the question. Here is my code :
private void createDirectory(File currentDirectory) {
File f = null;
try {
f = new File(currentDirectory.getCanonicalPath() + "/directory"
+ count);
boolean success = f.mkdir();
if (!success) {
Toast.makeText(currentContext,
f.getName() + " could not be created", 15).show();
}
} catch (IOException ioe) {
Toast.makeText(currentContext,
f.getName() + " could not be created", 15).show();
}
count++;
}
I am writing a small file manager in Android and I would like to add the possibility to create a directory. There is no exception and the variable success always return false. Can someone tell me what is wrong my code??
Thx for your advice !!
[EDIT]
BTW, When the phone is in Developpement mode, does an application has a write access on the sdcard? I am programming on my phone (Acer liquid)
回答1:
You have to add this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
By the way, not sure how you are getting the SDcard directory... but it must be this way:
File sdDir = Environment.getExternalStorageDirectory();
It's important, because some programmers use to think that the SDCard is always /sdcard, but it could change.
回答2:
You're going to need to add
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to your manifest file to tell Android to ask the user for your application to be allowed to.
回答3:
First, please use the File
constructor that takes a File
for your directory and a String
for your desired subdirectory.
Beyond that, most likely you are attempting to create a directory where you are not allowed, either because:
currentDirectory
does not exist, orcurrentDirectory
points to a place on the on-board flash storage where you are not allowed to write, orcurrentDirectory
points to a place on the external storage and you lack theWRITE_EXTERNAL_STORAGE
permission
回答4:
instead of boolean success = f.mkdir();
use
boolean success = f.mkdirs();
that solved my problem (i used the same reference code as you and had the same issue).
来源:https://stackoverflow.com/questions/4776426/how-to-create-a-directory-in-android