【问题标题】:Convert large bytesarray to file in kotlin在kotlin中将大字节数组转换为文件
【发布时间】:2020-03-29 15:32:18
【问题描述】:

嗨,我有一个很大的字节数组,我想转换为 sdcard 中的文件我使用了这段代码,但有时会崩溃 将字节数组转换为 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()
                }
            }
        }
    }

【问题讨论】:

    标签: java arrays kotlin fileinputstream fileoutputstream


    【解决方案1】:

    你可以使用 apache commons-io

    FileUtils.writeByteArrayToFile(File, ByteArray)
    

    【讨论】:

      【解决方案2】:

      你可以使用writeBytes函数:

      fun File.writeBytes(array: ByteArray)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-09
        • 2014-04-14
        • 2015-09-16
        • 2021-07-17
        • 1970-01-01
        • 2017-10-07
        相关资源
        最近更新 更多