-1

I am trying to save files from the asset folder to the android device's public directory e.g. "Downloads". Normal file read-write doesn't seem to work. How to do it?

I have tried this How to copy files from 'assets' folder to sdcard? but this didn't work.

fun copy() {
val bufferSize = 1024
val assetManager = context.assets
val assetFiles = assetManager.list("")

assetFiles.forEach {
    val inputStream = assetManager.open(it)
    val outputStream = FileOutputStream(File(this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), it))

    try {
        inputStream.copyTo(outputStream, bufferSize)
    } finally {
        inputStream.close()
        outputStream.flush()
        outputStream.close()
    }
}

}

Rohit J
  • 107
  • 7

1 Answers1

1

Make sure you have enabled runtime read/write permissions and after that simply you can use this code to save any file to a directory.

fun saveImageToExternalStorage(image:Bitmap) {
  val fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads"
  try
  {
    val dir = File(fullPath)
    if (!dir.exists())
    {
      dir.mkdirs()
    }
    val fOut:OutputStream = null
    val file = File(fullPath, "image.png")
    if (file.exists())
    file.delete()
    file.createNewFile()
    fOut = FileOutputStream(file)
    // 100 means no compression, the lower you go, the stronger the compression
    image.compress(Bitmap.CompressFormat.PNG, 100, fOut)
    fOut.flush()
    fOut.close()
  }
  catch (e:Exception) {
    Log.e("saveToExternalStorage()", e.message)
  }
}
Mr. Patel
  • 1,379
  • 8
  • 21
  • `you can use this code to save any file to a directory.` Any file? You are saving a bitmap only. Not even one file. And not from assets. – blackapps Nov 11 '19 at 12:17
  • @blackapps due that's a common sense to replace bitmap with your file i'm just giving you the logic to save to a directory do the rest on your own! – Mr. Patel Nov 12 '19 at 03:12