问题
I'm facing a problem with creation of folder inside Android/data folder. My code need to create folder, and copy a file from asset folder inside it. This is my code:
private File getFileForShare(String filename) {
try {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "/Android/data/" + context.getPackageName());
if (!folder.exists()) {
folder.mkdir();
}
AssetManager am = context.getAssets();
InputStream inputStream = am.open("audio/" + filename);
File f = new File(folder.getAbsolutePath(), filename);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
return f;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I obtain a FileNotFoundException when i initialize OutputStream object. Also, if i go to Android/data folder, no new folder with my app package name is created. Inside manifest i've set read and write storage permission. What's wrong?
回答1:
What's wrong?
The proper way to get a directory that, for the primary device owner, resides under Android/data/
on external storage, is just to call getExternalFilesDir()
on an available Context
. Replace:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "/Android/data/" + context.getPackageName());
with:
File folder = context.getExternalFilesDir();
来源:https://stackoverflow.com/questions/28129647/unable-to-create-folder-inside-android-data