6

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

Vikas Acharya
  • 3,550
  • 4
  • 19
  • 52

3 Answers3

7

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.

Vikas Acharya
  • 3,550
  • 4
  • 19
  • 52
  • plz tell me is it possible to paste that file inside android/data/ instead of android/data/"com.your.pkg_name " – Arun Goenka Aug 18 '22 at 01:38
0

You are trying to create file in root directory which is not permitted. You can create files in the internal storage/SD card using Environment.getExternalStorageDirectory(). Use the below code:

val myObj = File(Environment.getExternalStorageDirectory()+"/"+"filename.txt")

Note: Environment.getExternalStorageDirectory() is deprecated in API level 29 java

Please refer Environment.getExternalStorageDirectory() deprecated in API level 29 java for more details.

Alpha 1
  • 4,118
  • 2
  • 17
  • 23
0

Actual in June 2023

In order to write to Internal Storage from your activity, make use of this snippet:

    applicationContext.openFileOutput("filename.txt", Context.MODE_PRIVATE).use {
        it.write("your text".toByteArray())
    }

Note! Use applicationContext instead of context

However, now it is stronly advised to use DataStore: https://developer.android.com/topic/libraries/architecture/datastore