how to create a folder and file in internal storage using kotlin

4,528

ok got it,not specifying proper path.

        val data: String = "om namah shivaya"
        val path = this.getExternalFilesDir(null)

        val folder = File(path, "avalakki")
        folder.mkdirs()

        println(folder.exists()) // u'll get true 

        val file = File(folder, "file_name.txt")
        file.appendText("$data")

then to check this, navigate to

Android -> data -> com.your.pkg_name -> files ->

There will see files got created.

note:- we can use different paths

val path = this.externalCacheDir
Android -> data -> com.your.pkg_name -> cache ->

val path = this.externalMediaDirs.first()
Android -> media

val path = this.getExternalFilesDirs(null).first()
val path = Environment.getExternalStorageDirectory().getPath()

print and check what the path is.

Share:
4,528
Vikas Acharya
Author by

Vikas Acharya

Nothing special ! I don't like coding

Updated on December 21, 2022

Comments

  • Vikas Acharya
    Vikas Acharya over 1 year

    I'm trying to create a file and folder on my internal storage
    in manifest i have

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

    these permissions.

    fun test(view: View) {
            try {
                val myObj = File("filename.txt")
                if (myObj.createNewFile()) {
                    println("File created: " + myObj.name)
                } else {
                    println("File already exists.")
                }
            } catch (e: IOException) {
                println("An error occurred.")
                e.printStackTrace()
            }
        }
    }
    

    i got this

    An error occurred.
    java.io.IOException: Read-only file system
    

    i tried so many other thing from javatpoint to official java and kotlin tutorials. but none worked