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

时间:2017-06-27 04:58:36

标签: java android storage

我可以使用

创建一个文件
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" />

我只想将数据库文件备份到可访问的文件,然后我可以在手机/计算机上看到它。

1 个答案:

答案 0 :(得分:1)

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

这里有三种方法很重要:

  1. ContextCompat.checkSelfPermission()检查是否已获得许可
  2. ActivityCompat.requestPermissions()请求未获得许可
  3. onRequestPermissionsResult()在用户授予权限后执行所需操作
  4. Refer to this answer for the code and details