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.
You should write to the location /storage/emulated
directory. You avhave used openFileOutput()
. It points to where getFilesDir()
on Context returns. You can tell this because the documentation says:
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
To read from your location, use openFileInput()
, the corresponding method on Context with the same filename that you had passsed to the openFileOutput()
.