如何在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时,只有空白页,出了什么问题?
答案 0 :(得分: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()
}
答案 1 :(得分: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
}
}