这里是将downTaskEntity.downloadDetails中的文件进行拼接,打开第一个文件准备写入filehandleA,定义FILE_SIZE为600KB,如果单个文件小于FILE_SIZE,直接在filehandleA结尾拼接,如果大于FILE_SIZE,将该文件按照FILE_SIZE大小拆分并拼接到filehandleA结尾处。这样做的原因主要是直接写入大文件会有性能问题。
for (idx, obj) in downTaskEntity.downloadDetails.enumerated(){
filepath = obj.filePath
if idx == 0 {
filehandleA = FileHandle.init(forWritingAtPath: filepath)
} else {
fileSize = MDDownloadManager.getSize(filePath: filepath)
if fileSize < FILE_SIZE {
let data = NSData.init(contentsOfFile: filepath)
if data != nil {
filehandleA?.seekToEndOfFile()
filehandleA?.write(data! as Data)
}
} else {
filehandleB = FileHandle.init(forReadingAtPath: filepath)
let sizes = (fileSize + FILE_SIZE / 2) / FILE_SIZE
for index in 0...sizes {
filehandleA?.seekToEndOfFile()
filehandleB?.seek(toFileOffset: UInt64(index*FILE_SIZE))
if index == sizes {
let data = filehandleB?.readDataToEndOfFile()
filehandleA?.write(data!)
filehandleB?.closeFile()
self.deleteFileAtPath(path: filepath)
} else {
let data = filehandleB?.readData(ofLength: FILE_SIZE)
filehandleA?.write(data!)
}
}
}
}
}
filehandleA?.closeFile()
filehandleB?.closeFile()
欢迎大神批评指正哦!