Home > Back-end >  Creating directories within Android internal storage
Creating directories within Android internal storage

Time:08-18

I have some problems with creating and then listing directories within Android internal storage.

This is the kotlin code I execute in my app:

    var dirStatus = applicationContext.getDir("One", MODE_PRIVATE)
    println("dirStatus = " dirStatus)
    dirStatus = applicationContext.getDir("Two", MODE_PRIVATE)
    println("dirStatus = " dirStatus)
    dirStatus = applicationContext.getDir("Three", MODE_PRIVATE)
    println("dirStatus = " dirStatus)

This is what I see in the console once the code above is executed:

    I/System.out: dirStatus = /data/user/0/me.soft.myapp/app_One
    I/System.out: dirStatus = /data/user/0/me.soft.myapp/app_Two
    I/System.out: dirStatus = /data/user/0/me.soft.myapp/app_Three
    D/HwAppInnerBoostImpl: asyncReportData me.soft.myapp,2,1,1,0 interval=249
    I/software.crayo: Starting profile saver IsSaveProfileNow end.

Now here is my question, assuming that three empty directories (One,Two,Three) have just been created. What is the code that will allow me to list those three directories?

If I am asking this is because the code below which I expected to do the job did not work:

    val directory:File
    directory = getFilesDir()
    val files: Array<File> = directory.listFiles()
    println("Files count: " files.size)
    for (f in files) {
        println("Name:" f.name)
    }

CodePudding user response:

public abstract File getFilesDir() means /data/user/0/xxx/files not /data/user/0/xxx/

val a = applicationContext.getDir("aaaa", Context.MODE_PRIVATE)
applicationContext.getDir("bbbb", Context.MODE_PRIVATE)
applicationContext.getDir("cccc", Context.MODE_PRIVATE)

// print nothing
applicationContext.filesDir.listFiles()?.forEach { file ->
    Log.d("MainActivity", "file path: ${file.absolutePath}")
}

// print a parent directory
a.parentFile?.listFiles()?.forEach { file ->
    Log.d("MainActivity", "file path: ${file.absolutePath}")
}

CodePudding user response:

I am not sure but It may be helpful to you.

val myFile = File(path)
val files: Array<File> = myFile.listFiles()
for (f in files) {
    if (f.isDirectory) {
        // Do your stuff  
        Log.e("TAG", "onCreate : "  f.name ) 
    }
}
  • Related