4

如何从 Android 上的 http 响应中正确保存 pdf 文件?通过 rest API 接收字节流。我试过这个:

try
{
File outputFile = new File("/storage/emulated/0/Android/data/package/files/", "cot.pdf");
FileOutpuStream fos = new FileOutputStream(outputFile);
byte [] bytes = data.getBytes();//byte stream response
fos.write(bytes);
fos.flush();
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}

文件和数据都写入了,但是打开pdf时,只有空白页,这是怎么回事?

4

2 回答 2

0

试试这个用例:

class SaveInputStreamAsPdfFileUseCase {

    suspend operator fun invoke(inputStream: InputStream, applicationContext: Context): File? {
        var outputFile: File? = null
        withContext(Dispatchers.IO) {
            try {
                val directory = ContextCompat.getExternalFilesDirs(applicationContext, "documents").first()
                val outputDir = File(directory, "outputPath")
                outputFile = File(outputDir, UUID.randomUUID().toString() + ".pdf")
                 if (!outputDir.exists()) {
                     outputDir.mkdirs()
                }
                val outputStream = FileOutputStream(outputFile, false)
                inputStream.use { fileOut -> fileOut.copyTo(outputStream) }
                outputStream.close()
            } catch (e: Exception) {
                // Something went wrong
            }
        }
        return outputFile
    }
}
于 2021-02-13T22:41:53.923 回答
0
  fun download_pdf(data : ByteArray){
     val fileOutputStream =     FileOutputStream("/storage/emulated/0/dndinfoways.pdf")
    val inputStream: InputStream = ByteArrayInputStream(data)
    var data: Int
    while (inputStream.read().also { data = it } >= 0) {
        fileOutputStream.write(data)
    }
    inputStream.close()
}
于 2020-09-05T11:22:25.553 回答