无法使用mkdir在Android Q中创建文件夹

时间:2019-07-05 07:44:53

标签: java android mkdir androidq

除了android Q以外,我的应用程序创建所有android版本的文件夹都没有问题,我不知道为什么我的代码在android q中不起作用

这是我的代码:

File dir = new File("/sdcard/test");
       try{
              if(dir.mkdir()) {
                      Log.d("DOWNLOAD","Directory created");
              } else {
                     Log.d("DOWNLOAD","Directory is not created");
              }
            }catch(Exception e){
                  e.printStackTrace();
        }

2 个答案:

答案 0 :(得分:3)

在Q中,如果您要访问的文件不是常见的音乐或媒体文件,例如sdcard/test,则需要执行以下操作:

  

为了访问其他应用程序创建的任何其他文件,包括“下载”目录中的文件,您的应用程序必须使用存储访问框架,该框架允许用户选择特定文件。

引用src:http://developer.android.com/preview/privacy/scoped-storage

// Here are some examples of how you might call this method.
// The first parameter is the MIME type, and the second parameter is the name
// of the file you are creating:
//
// createFile("text/plain", "foobar.txt");
// createFile("image/png", "mypicture.png");

// Unique request code.
private const val WRITE_REQUEST_CODE: Int = 43
...
private fun createFile(mimeType: String, fileName: String) {
    val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
        // Filter to only show results that can be "opened", such as
        // a file (as opposed to a list of contacts or timezones).
        addCategory(Intent.CATEGORY_OPENABLE)

        // Create a file with the requested MIME type.
        type = mimeType
        putExtra(Intent.EXTRA_TITLE, fileName)
    }

    startActivityForResult(intent, WRITE_REQUEST_CODE)
}

示例src https://developer.android.com/guide/topics/providers/document-provider

答案 1 :(得分:0)

 <manifest ... >
 <!-- This attribute is "false" by default on apps targeting Android Q. ->
  <application android:requestLegacyExternalStorage="true" ... >

 </application>
</manifest>