iosswiftfilesystemsfilemerge

Swift - merge files


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)

Solution

  • 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()
      }
    }