How to create a directory and record a txt file in the SD external memory

2

I'm doing an app in which I'm trying to create the "Download / Datax" directory and write txt files to external SD memory and I'm using this code:

File directorioExt = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOCUMENTS ), "/Download/Datax/" );
if (!directorioExt.exists()) {
   File directoriox = new File( Environment.getExternalStorageDirectory() + "/Download/Datax/" );
   directoriox.mkdirs();
   }

But it is not possible to create the directory in the external memory. I have also placed in the manifest:

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

Can someone tell me how to achieve this?

    
asked by W1ll 29.11.2018 в 23:15
source

1 answer

2

Actually your code is correct:

File directorioExt = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOCUMENTS ), "/Download/Datax/" );
if (!directorioExt.exists()) {
   File directoriox = new File( Environment.getExternalStorageDirectory() + "/Download/Datax/" );
   directoriox.mkdirs();
}

One of the causes why you could not create the specified directory is not having permission WRITE_EXTERNAL_STORAGE , for devices with Android 6.0 operating system it is not enough to define it in the file AndroidManifest.xml , you must require it manually:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
    //Verifica permisos para Android 6.0+
    int permissionCheck = ContextCompat.checkSelfPermission(
            this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        Log.i("Mensaje", "No se tiene permiso para leer.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
    } else {
        Log.i("Mensaje", "Se tiene permiso para leer!");
    }
}

Review this answer:

Error showing the external file directory in an AlertDialog in android 6.0 (READ_EXTERNAL_STORAGE / WRITE_EXTERNAL_STORAGE)

    
answered by 30.11.2018 в 17:49