Michel
Michel

Reputation: 11749

Creating directories within Android internal storage

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)
    }

Upvotes: 0

Views: 1642

Answers (2)

haoxiqiang
haoxiqiang

Reputation: 537

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}")
}

enter image description here

Upvotes: 1

Bhavin Solanki
Bhavin Solanki

Reputation: 510

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 ) 
    }
}

Upvotes: 0

Related Questions