【发布时间】:2020-10-18 20:28:12
【问题描述】:
我正在尝试从 http 链接下载 mp3 文件并将文件保存到本地存储。我尝试过的所有代码都会保存一个损坏的文件,该文件的大小是应有的两倍。 文件应该是 1,204,787 保存的文件是 2,478,272
我要下载的文件是:rise-stage.bioinf.unc.edu/cue_audio/sampleaudio.mp3 –
手动下载时播放正常。
fun downloadFilea(url:String , localFileName:String)
{
val request: Request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
println("error"+e.toString())
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
var uri = dataMgr.getLocalURI(localFileName)
var file = File(uri)
val body = response.body
val contentLength = body!!.contentLength()
val source = body.source()
val DOWNLOAD_CHUNK_SIZE:Long = 2048
val sink: BufferedSink = file.sink().buffer()
var totalRead: Long = 0
var read: Long = 0
while (source.read(sink.buffer(), DOWNLOAD_CHUNK_SIZE).also {
read = it
} != -1L) {
totalRead += read
val progress = (totalRead * 100 / contentLength).toInt()
}
sink.writeAll(source)
sink.flush()
sink.close()
Log.d(logTag, "downloaded file")
}
})
}
【问题讨论】:
-
This approach 代码更少,效率更高,并且适合我。
-
@CommonsWare 其中一些代码已被弃用,也会产生同样的问题。
-
您可以看到它正在使用here,并且我没有看到任何弃用警告。即使我将它更新到最新的 OkHttp (4.7.2),也没有弃用警告。
-
这段代码似乎适用于文本文件,但是当它是一个 mp3 文件时,它会生成一个损坏的文件,该文件的大小是应有的两倍。