How to create a file in an SDCARD directory

后端 未结 5 1896
长情又很酷
长情又很酷 2020-12-10 07:38

I want to create a file(not created) in a directory(not created) in the SDCARD. How doing it ?

Thank you.

相关标签:
5条回答
  • 2020-12-10 08:04

    Try the following example:

    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        //handle case of no SDCARD present
    } else {
        String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
        //create folder
        File folder = new File(dir); //folder name
        folder.mkdirs();
    
        //create file
        File file = new File(dir, "filename.extension");
    }
    

    Don't forget to add the permission to your AndroidManifest:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    0 讨论(0)
  • 2020-12-10 08:12

    The problem is that mkdirs() is called on a File object containing the whole path up to the actual file. It should be called on a File object containing the Path (the directory) and only that. Then you should use another File object to create the actual file.

    0 讨论(0)
  • 2020-12-10 08:23

    You should also have to add permission to write to external media. Add following line in the application manifest file, somewhere between <manifest> tags, but not inside <application> tag:

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

    0 讨论(0)
  • 2020-12-10 08:23

    See here why creating files on root of the SD card is a bad idea

    0 讨论(0)
  • 2020-12-10 08:27

    Use This:

    DocumentFile tempDir = DocumentFile.fromSingleUri(context,targetDirectoryUri);
    DocumentFile newDocumentFile = tempDir.createFile(type,name);
    

    "targetDirectoryUri" is uri of the directory you want to put the file into it. This is the only solution! After Api 19 you can not write on SDCard, so you must use DocumentFile instead File. In addition, you must also take SDCard permission. To learn how to do this and get the targetDirectoryUri, please read this.

    0 讨论(0)
提交回复
热议问题