Skip to content

Commit

Permalink
修复一个很深的BUG。
Browse files Browse the repository at this point in the history
  • Loading branch information
xiazunyang committed Dec 2, 2021
1 parent 4c26481 commit b3b3850
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
2 changes: 1 addition & 1 deletion http/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ plugins {
}

group = "com.github.xiazunyang"
version = "1.0.0"
version = "1.0.1"

tasks.withType<KotlinCompile> {
kotlinOptions {
Expand Down
16 changes: 10 additions & 6 deletions http/src/main/kotlin/cn/numeron/okhttp/ProgressInterceptor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class ProgressInterceptor : Interceptor {
parentFile.mkdirs()
}

val existLength = file.length()
var existLength = file.length()
//如果文件存在,并且与要下载的文件一致,则直接返回
if (contentLength > 0 && existLength == contentLength) {
response.closeQuietly()
Expand All @@ -98,6 +98,8 @@ class ProgressInterceptor : Interceptor {
if (file.exists()) {
file.delete()
}
//因为已经已删除,所以要将此变量置0
existLength = 0
}
//如果文件已存在一部分,则重新发起请求,获取其余数据
if (existLength > 0) {
Expand All @@ -116,7 +118,7 @@ class ProgressInterceptor : Interceptor {
}

//将请求体中的数据定入到文件中
responseBody.writeTo(file)
responseBody.writeTo(file, existLength)

//写完文件数据后,构建一个新的回调并返回
val fileResponseBody = FileResponseBody(file, contentType)
Expand All @@ -127,10 +129,12 @@ class ProgressInterceptor : Interceptor {
/**
* 使用RandomAccessFile将数据写入到文件
*/
private fun ResponseBody.writeTo(file: File) {
private fun ResponseBody.writeTo(file: File, existLength: Long) {
//使用RandomAccessFile将数据写入到文件
val outputFile = RandomAccessFile(file, "rws")
outputFile.seek(file.length())
if (existLength > 0) {
outputFile.seek(existLength)
}
//执行写入操作
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var readLength = source().read(buffer)
Expand All @@ -146,8 +150,8 @@ class ProgressInterceptor : Interceptor {
* 根据[fileOrPath]的类型、响应信息以及请求信息中判断文件名及保存位置
*/
private fun getStoredFile(fileOrPath: File, response: Response, request: Request): File {
return if (fileOrPath.exists() && fileOrPath.isFile || fileOrPath.extension.isNotEmpty()) {
//如果文件存在,并且是一个文件,或者文件名有扩展名,则将其作为保存数据的文件
return if (fileOrPath.isFile || fileOrPath.extension.isNotEmpty()) {
//如果是一个文件,或者文件名有扩展名,则将其作为保存数据的文件
fileOrPath
} else {
//否则就是存放的目录,获取文件名并在该目录下创建文件
Expand Down

0 comments on commit b3b3850

Please sign in to comment.