在内部存储中创建目录

Creating directory in internal storage

我认为我的智能手机是哑铃。 尝试创建一个文件夹,但似乎无法创建。 我是 运行 CyanogenMod,不知道这是否会让它变得疯狂。

这是我一直在测试的:

File folder = new File(getFilesDir() + "theFolder");
if(!folder.exists()){
folder.mkdir();
}

还有这个方法:

File folder = getDir("theFolder",Context.MODE_PRIVATE);

您忘记在添加文件名之前添加“/”,因此您的路径编译如下:

/data/data/com.myPackageNametheFolder

File folder = new File(getFilesDir() + "/" + "theFolder");

File folder = new File(getFilesDir(),"theFolder");

你会得到这个

/data/data/com.myPackageName/theFolder

PS : There is no dumb phone all phones are Smart Phones 'Bad dum tss'

这个答案是旧的,我更新了它。我包括内部和外部存储。我会一步步解释的。

步骤 1) 您应该声明适当的 Manifest.xml 权限;对于我们的情况,这两个就足够了。此步骤还需要 6.0 之前和 6.0 之后的版本:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

步骤 2) 在这一步中,我们将检查写入外部存储的权限,然后将执行我们想要的任何操作。

public static int STORAGE_WRITE_PERMISSION_BITMAP_SHARE =0x1;

public Uri saveBitmapToFileForShare(File file,Uri uri){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
    && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

//in this side of if we don't have permission 
//so we can't do anything. just returning null and waiting user action

    requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
   "permission required for writing external storage bla bla ..."
                REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
        return null;
    }else{
        //we have right about using external storage. do whatever u want.
        Uri returnUri=null;
        try{
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver() ,uri);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            returnUri=Uri.fromFile(file);
        }
        catch (IOException e){
            //can handle for io exceptions
        }

        return returnUri;
    }

}

步骤 3 ) 处理权限基本原理并显示对话框,请阅读评论以获取信息

/**
 * Requests given permission.
 * If the permission has been denied previously, a Dialog will prompt the user to grant the
 * permission, otherwise it is requested directly.
 */
protected void requestPermission(final String permission, String rationale, final int requestCode) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
        showAlertDialog("Permission required", rationale,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(BasePermissionActivity.this,
                                new String[]{permission}, requestCode);
                    }
                }, getString(android.R.string.ok), null, getString(android.R.string.cancel));
    } else {
        ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
    }
}

/**
 * This method shows dialog with given title & content.
 * Also there is an option to pass onClickListener for positive & negative button.
 *
 * @param title                         - dialog title
 * @param message                       - dialog content
 * @param onPositiveButtonClickListener - listener for positive button
 * @param positiveText                  - positive button text
 * @param onNegativeButtonClickListener - listener for negative button
 * @param negativeText                  - negative button text
 */
protected void showAlertDialog(@Nullable String title, @Nullable String message,
                               @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                               @NonNull String positiveText,
                               @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                               @NonNull String negativeText) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
    builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
    mAlertDialog = builder.show();
}

步骤 4 ) 获取权限结果 Activity :

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case STORAGE_WRITE_PERMISSION_BITMAP_SHARE:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                shareImage();
            }else if(grantResults[0]==PackageManager.PERMISSION_DENIED){
                //this toast is calling when user press cancel. You can also use this logic on alertdialog's cancel listener too.
                Toast.makeText(getApplicationContext(),"you denied permission but you need to give permission for sharing image. "),Toast.LENGTH_SHORT).show();
            }
            break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

步骤 5) 如果使用内部存储。您无需检查使用内部存储的运行时权限。

//this creates a png file in internal folder
//the directory is like : ......data/sketches/my_sketch_437657436.png
File mFileTemp = new File(getFilesDir() + File.separator
                + "sketches"
                , "my_sketch_"
                + System.currentTimeMillis() + ".png");
        mFileTemp.getParentFile().mkdirs();

您可以阅读此页面以获取有关运行时权限的信息:runtime permission requesting

我的建议: 您可以创建一个 Activity 负责此权限,例如 BasePermissionActivity 并在其中声明方法 @Step 3。然后你可以扩展它并在你想要的地方调用你的请求权限。

我也搜索了一下,找到了代码@Step 3 Github link 以防你想检查:yalantis/ucrop/sample/BaseActivity.java