Unable to create folder inside Android/data

痞子三分冷 提交于 2019-12-11 01:07:00

问题


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

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