Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert large bytesarray to file in kotlin

hi i have a large bytesarray and i want to convert to file in sdcard i used this code but crash sometimes what is the best way to convert bytesarray to file in kotlin?

private fun writeBytesToFileClassic(
        bFile: ByteArray,
        fileDest: String
    ) {
        var fileOuputStream: FileOutputStream? = null
        try {
            fileOuputStream = FileOutputStream(fileDest)
            fileOuputStream.write(bFile)
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (fileOuputStream != null) {
                try {
                    fileOuputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }
fun ExtractPdf(byteArray: ByteArray, filename: String){
        var fileInputStream: FileInputStream? = null
        val file: File = File(UPLOAD_FOLDER())
        if (!file.exists()){
            file.mkdir()
        }
        try {
            //save bytes[] into a file
            writeBytesToFileClassic(byteArray, UPLOAD_FOLDER() + filename)
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

1 Answers

You can use the writeBytes function:

fun File.writeBytes(array: ByteArray)
like image 116
André Jesus Avatar answered Feb 06 '26 20:02

André Jesus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!