如何在 Android 上的可访问文件夹中创建文件? (非根)

How can I create a File in an accessible folder on Android? (non-root)

我可以使用

创建文件
File directory = cw.getDir("media", Context.MODE_PRIVATE);
 //directory.mkdirs();
 File backupDB = new File(directory, backupname);

我也试过了

 File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"images");

 File backupDB = new File(directory, backupname);

运气不好,这是完整的方法

   public String backUpDatabase(String backupname){

      try {
       File directory = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)));
            File currentDB = new File(DBlocation);
            File folder = new File("/sdcard/exports/Database_Backups/");
            File backupDB = new File(directory, backupname);

            if (!(folder.exists() && folder.isDirectory())) {
                folder.mkdirs();
            }

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
            else{
                return "didnt work";
            }

        } catch (Exception e) {
          return "didnt work";
        }

        return backupname.toString();

    }

我已经使用权限了。

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

我只想将数据库文件备份到一个可访问的文件,然后我可以在 phone/computer 本身上看到该文件。

要在 android Lollipop 及更高版本上写入外部存储,您需要 request permission at run time.

这里三个方法很重要:

  1. ContextCompat.checkSelfPermission()检查是否给了权限
  2. ActivityCompat.requestPermissions()如果没有权限请求
  3. onRequestPermissionsResult() 在用户授予权限后执行所需的操作

Refer to this answer for the code and details