我的文档目录中保存了一个大型视频。我想检索这个视频并删除它的前 5 个字节。对于超过 300 MB 的大型视频文件,使用 [NSData(contentsOf: videoURL)] 会导致内存问题错误。
我通过Swift:Loading a large video file (over 700MB) into memory 发现我们需要使用 [InputStream] 和 [OutputStream] 或 [NSFileHandle] 处理大文件。如何使用它?
示例代码如下:
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first{
let videoURL = URL(fileURLWithPath: dirPath).appendingPathComponent(filePath)
do {
let videoData = try NSData(contentsOf: videoURL)
let mutabledata = videoData.mutableCopy() as! NSMutableData
mutabledata.replaceBytes(in: NSRange(location: 0, length: 5), withBytes: nil, length: 0)
}catch {
print("Error Writing video: \(error)")
}