Pythogen
Pythogen

Reputation: 640

How can I read the contents of a DocumentFile in Android?

I have added a feature to an application to allow the user to create a local backup on external storage. That part is working great, but I am having trouble restoring that back up.

Using the SAF, I have found an easy way for the user to select the file they are wanting to restore. The file they choose comes back to the app as a DocumentFile

How can I open the DocumentFile and read its contents on API 26 and up?

So far I tried 2 things and neither worked:

1) new File(myDocumentFile.getUri().getPath())

2) I've tried this answer but it didn't work. It is also so hacky and I don't really need access to the java.io.File I just need a way to read the contents.

How does Google want us to approach reading user's files?

Upvotes: 1

Views: 1595

Answers (1)

fbiego
fbiego

Reputation: 418

Kotlin code to read lines from a text file (where 'file' is a DocumentFile)

val inputStream = contentResolver.openInputStream(file.uri)
val reader = BufferedReader(InputStreamReader(inputStream))
val lines = reader.readLines()

Upvotes: 5

Related Questions