I want to read data from .txt
file from /storage/emulated application-specific path. I have written data successfully in same file but not able to read it.
Code to write data in txt file.
val writer: FileOutputStream = openFileOutput(file.absolutePath, MODE_PRIVATE)
writer.write(str1.toByteArray())
writer.flush()
writer.close()
Trying to read data from same file.
val text = StringBuilder()
val br = BufferedReader(FileReader(file))
var line: String?
while (br.readLine().also { line = it } != null) {
text.append(line)
text.append('\n')
}
br.close()
line returning null value.
CodePudding user response:
I want to read data from .txt file from /storage/emulated application-specific path. I have written data successfully in same file but not able to read it.
You did not write to a location in a /storage/emulated
directory. You used openFileOutput()
. That writes to a different location. To read from that location, use openFileInput()
, the corresponding method on Context
. Be sure to use the same filename that you passed to openFileOutput()
.
CodePudding user response:
Try adding android:requestLegacyExternalStorage="true" to your manifest.
Or change it to comply to Android 11's new scoped storage system. See https://developer.android.com/about/versions/11/privacy/storage
CodePudding user response:
Read string from .txt file
Kotlin
val reader = FileReader(path)
val txt = reader.readText()
reader.close()