Here a snippet related to @CommonsWare answer.
Launch the file picker with Intent.ACTION_OPEN_DOCUMENT_TREE
startActivityForResult(
Intent.createChooser(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), "Choose directory"),
IMPORT_FILE_REQUEST
)
Receive the Uri
of the selected directory from file picker
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
IMPORT_FILE_REQUEST -> {
if (resultCode != Activity.RESULT_OK) return
val uri = data?.data ?: return
// get children uri from the tree uri
val childrenUri =
DocumentsContract.buildChildDocumentsUriUsingTree(
uri,
DocumentsContract.getTreeDocumentId(uri)
)
// get document file from children uri
val tree = DocumentFile.fromTreeUri(this, childrenUri)
// get the list of the documents
tree?.listFiles()?.forEach { doc ->
// get the input stream of a single document
val iss = contentResolver.openInputStream(doc.uri)
// prepare the output stream
val oss = FileOutputStream(File(filesDir, doc.name))
// copy the file
CopyFile { result ->
println("file copied? $result")
}.execute(iss, oss)
}
}
}
}
Copy file with AsyncTask
(feel free to use threads, coroutines..)
class CopyFile(val callback: (Boolean) -> Unit) :
AsyncTask<Closeable, Int, Boolean>() {
override fun doInBackground(vararg closeables: Closeable): Boolean {
if (closeables.size != 2) throw IllegalArgumentException("two arguments required: input stream and output stream")
try {
(closeables[0] as InputStream).use { iss ->
(closeables[1] as OutputStream).use { oss ->
iss.copyTo(oss)
return true
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
override fun onPostExecute(result: Boolean) {
callback.invoke(result)
}
}