在内部存储中创建目录

时间:2016-02-17 23:18:49

标签: android file mkdirs

我认为我的智能手机是一部哑铃。 试图创建一个文件夹,似乎它不会被创建。 我正在运行CyanogenMod并且不知道这是否会让它变得疯狂。

这就是我一直在测试的:

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

还有这个意见:

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

2 个答案:

答案 0 :(得分:3)

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

步骤1)您应该声明适当的Manifest.xml权限;对于我们的情况,这2个就够了。此步骤还需要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)获取权限结果进入活动:

@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链接:yalantis/ucrop/sample/BaseActivity.java

答案 1 :(得分:1)

你忘了添加&#34; /&#34;在添加文件名之前,您的路径编译如下:

<强> /data/data/com.myPackageNametheFolder

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

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

你会得到这个

<强> /data/data/com.myPackageName/theFolder

  PS:没有哑巴手机所有手机都是智能手机&#39; Bad dum tss&#39;