Can't create folder on external storage on android

后端 未结 8 1062
独厮守ぢ
独厮守ぢ 2020-12-05 11:25

My development phone is a Nexus 5, running Android 4.4.2.

In my application, I am attempting to create a folder on external storage that wi

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 11:56

    Typically, I do this:

    /**
     * Return a dedicated directory named "MyApp" at the top of external storage
     */
    public static file getDataDir() {
        File sdcard = Environment.getExternalStorageDirectory();
        if( sdcard == null || !sdcard.isDirectory() ) {
            // TODO: warning popup
            Log.w(TAG, "Storage card not found " + sdcard);
            return null;
        }
        File dataDir = new File(sdcard, "MyApp");
        if( !confirmDir(dataDir) ) {
            // TODO: warning popup
            Log.e(TAG, "Unable to create " + dataDir);
            return null;
        }
        return dataDir;
    }   
    
    private static boolean confirmDir(File dir) {
        if (dir.isDirectory()) return true;  // already exists
        if (dir.exists()) return false;      // already exists, but is not a directory
        return dir.mkdirs();                 // create it
    }       
    

    Also, add this permission to your manifest:

    
    

    If you want private storage (typically under /data/) for your app (not on sdcard), then look into getDir(), getFilesDir(), fileList(), openFileInput(), openFileOutput(), etc.

    There are also helper functions to get private directories within the sdcard for API 8 and above: getExternalFilesDir(), getExternalCacheDir(), etc.

提交回复
热议问题