Skip to content

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

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: " +
            } else {
                println("File already exists.")
        } catch (e: IOException) {
            println("An error occurred.")

i got this

An error occurred. Read-only file system

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


ok got it,not specifying proper path.

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

        val folder = File(path, "avalakki")

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

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

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.