Download files in storage – Android kotlin
Previously, we created a tutorial to show you how you can download an image in your storage using Java. In this tutorial, we will show you how you can download any file in your android phone’s storage using Kotlin. First, you need to create a file named “DownloadImageTask.kt” and write the following code in it:
class DownloadImageTask(
var imagePath: String?,
var fileName: String?
) : AsyncTask<Void, Void, Void>() {
var cachePath: String = ""
override fun doInBackground(vararg voids: Void?): Void? {
try {
val root =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
val directoryPath = File(root.absolutePath + "/")
if (!directoryPath.exists()) {
directoryPath.mkdir()
}
val cachePath = File("$directoryPath/$fileName")
cachePath.createNewFile()
val buffer = ByteArray(1024)
var bufferLength: Int
val url = URL(imagePath)
val urlConnection = url.openConnection() as HttpURLConnection
urlConnection.requestMethod = "GET"
urlConnection.doOutput = false
urlConnection.connect()
val inputStream = urlConnection.inputStream
val fileOutput = FileOutputStream(cachePath)
while (inputStream.read(buffer).also { bufferLength = it } > 0) {
fileOutput.write(buffer, 0, bufferLength)
}
fileOutput.write(buffer)
fileOutput.close()
inputStream.close()
this.cachePath = cachePath.toString()
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: ProtocolException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
override fun onPostExecute(aVoid: Void?) {
// when the operation is done
// you can use this.cachePath here
}
}
Now, whenever you want to download any file, you just need to run the following line passing the file’s absolute path in the first parameter. And the file name as the second parameter. The second parameter file name will be the name that will be saved in your phone’s storage.
DownloadImageTask("https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/stsci-01gfnn3pwjmy4rqxkz585bc4qh.png", "nasa.png")
.execute()
That’s how you can download any HTTP file in your android phone’s storage using Kotlin. If you face any problem in following this, kindly do let me know in the comments section below.