Swift-合并文件 [英] Swift - merge files

查看:153
本文介绍了Swift-合并文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift/iOS中合并文件? FileManager可以移动和复制项目,但是我对合并文件一无所知.我想要类似的东西

How can I merge files in Swift / iOS ? The FileManager can move and copy items but I've seen nothing about merging files. I'd like to have something like

FileManager.default.merge(files: [URL], to location: URL) throws

文件可能很大,所以我宁愿避免将其数据传递到内存中.

Files can potentially be big, so I'd rather avoid having to pass their data in memory.

===这是我自己的内存合并:

=== here is my own in memory merge:

let data = NSMutableData()
files.forEach({ partLocation in
  guard let partData = NSData(contentsOf: partLocation) else { return }
  data.append(partData as Data)
  do {
    try FileManager.default.removeItem(at: partLocation)
  } catch {
    print("error \(error)")
  }
})
data.write(to: destination, atomically: true)

推荐答案

这是我自己的解决方案(感谢@Alexander提供指导)

Here is my own solution (thanks @Alexander for the guidance)

extension FileManager {
  func merge(files: [URL], to destination: URL, chunkSize: Int = 1000000) throws {
    try FileManager.default.createFile(atPath: destination.path, contents: nil, attributes: nil)
    let writer = try FileHandle(forWritingTo: destination)
    try files.forEach({ partLocation in
      let reader = try FileHandle(forReadingFrom: partLocation)
      var data = reader.readData(ofLength: chunkSize)
      while data.count > 0 {
        writer.write(data)
        data = reader.readData(ofLength: chunkSize)
      }
      reader.closeFile()
    })
    writer.closeFile()
  }
}

这篇关于Swift-合并文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆