我正在用Kotlin Android应用程序访问API端点。在此API调用中,我返回一个字节数组。我想看到的是一种将字节数组转换为pdf文件并将其保存在手机下载文件夹中的方法。
private suspend fun getIDCard(sessionID: String?, carriermemid: String?): ByteArray? {
var results: String = ""
val postData = "{\"sessionid\": \" $sessionID\"}"
val outputStreamWriter: OutputStreamWriter
var byteArray: ByteArray? = null
val url: URL = URL(idURL + carriermemid)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
try {
conn.setRequestProperty(apiConfig.typeKey, apiConfig.typeValueJSON)
conn.setRequestProperty("Accept", "application/json")
conn.setRequestProperty("sessionid", sessionID)
conn.requestMethod = apiConfig.methodGet
val responseCode: Int = conn.responseCode
println("Response Code :: $responseCode")
//returning 404
return if (responseCode == HttpURLConnection.HTTP_OK) {// connection ok
var out: ByteArrayOutputStream? = ByteArrayOutputStream()
val `in`: InputStream = conn.inputStream
var bytesRead: Int
val buffer = ByteArray(1024)
while (`in`.read(buffer).also { bytesRead = it } > 0) {
out!!.write(buffer, 0, bytesRead)
}
out!!.close()
byteArray = out.toByteArray()
return byteArray
} else {
return byteArray
}
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
conn.disconnect()
}
return byteArray
}
这将获得Android下载目录,并将字节数组写为PDF文件(假设字节数组包含PDF)。将File.createTempFile更改为您喜欢的任何文件(无需创建临时文件):
fun writeBytesAsPdf(bytes : ByteArray) {
val path = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
var file = File.createTempFile("my_file",".pdf", path)
var os = FileOutputStream(file);
os.write(bytes);
os.close();
}
您还必须将android.permission.WRITE_EXTERNAL_STORAGE添加到清单中。
查看How to download PDF file with Retrofit and Kotlin coroutines?,您可以使用:
private const val BUFFER_SIZE = 4 * 1024
private fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
inputStream.use { input ->
val outputStream = FileOutputStream(outputFile)
outputStream.use { output ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val byteCount = input.read(buffer)
if (byteCount < 0) break
output.write(buffer, 0, byteCount)
}
output.flush()
}
}
}
或
private fun InputStream.saveToFile(file: String) = use { input ->
File(file).outputStream().use { output ->
input.copyTo(output)
}
}
还应该创建文件。
private fun createFile(context: Context, name: String): File? {
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
var file = File("$storageDir/$name.pdf")
return storageDir?.let { file }
}