1

Am trying to download media file from server to android default Downloads directory,but on storing the media in downloads i got exception java.io.FileNotFoundException: Download/01-21-2022 04:15.jpeg (No such file or directory)

here is my code

val fileName = message.attributes.jsonObject!!.get("fileName")
val contentLength = response.body()!!.contentLength()
val file = File(Environment.DIRECTORY_DOWNLOADS, fileName as String)
responseBody.byteStream().apply {
    file.outputStream().use { fileOut ->
    var bytesCopied = 0
    val buffer = ByteArray(8*1024)
    var bytes = read(buffer)
    while (bytes >= 0) {
     fileOut.write(buffer, 0, bytes)
     bytesCopied += bytes
     bytes = read(buffer)
     reportStatus(((bytesCopied * 100) / contentLength).toInt())
    }
   }
  }
  • `Download/01-21-2022 04:15.jpeg (No such file or directory)` Indeed. That is a non existing path. Its a relative path and you should use a full path. – blackapps Feb 07 '22 at 10:25
  • @blackapps am new to android can you suggest how can i get full path for downloads directory – Rahul Saini Feb 07 '22 at 10:48
  • Use `context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)` See: [Environment.getExternalStorageDirectory() deprecated in API level 29 java](https://stackoverflow.com/a/57116787) – Adinia Feb 07 '22 at 11:05

2 Answers2

0

You have all to fix this. "No such file or directory". Create file before usage. Try without apply, with verification that file was created. Be sure, that you have access to this directory.

-1

val file = File(Environment.DIRECTORY_DOWNLOADS, fileName as String)

You mean:

val file = File(Environment.getExternalStoragePyblicDirectory(Environment.DIRECTORY_DOWNLOADS),  fileName as String)
blackapps
  • 8,011
  • 2
  • 11
  • 25