Swift:解压文件 [英] Swift: unzipping file
问题描述
我正在尝试使用本机 libcompression
库从 zip 文件中的 txt 文件中获取 String
.其实我使用的代码来自
I’m trying to get String
from txt file inside the zip file using native libcompression
library. Actually I use the code from
起初,我在做:
let zip = try? Data(contentsOf: "/.../test.zip")
let tmp: Data? = zip?.unzip()
let txt: String? = String(data: tmp!, encoding: .utf8)
但是我如何获取 zip 文件的内容以及如何从某个 txt 文件中获取数据?
But how do I get the contents of zip file and how do I get data from certain txt file?
推荐答案
ZIP Foundation 支持访问个人ZIP 档案中的条目.
您必须通过将文件 URL 传递给 Archive
初始化程序来初始化存档.
之后,您可以通过下标访问特定条目:
ZIP Foundation supports accessing individual entries in ZIP archives.
You have to initialize an archive by passing a file URL to the Archive
initializer.
Afterwards you can access a specific entry via subscripting:
let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var archiveURL = URL(fileURLWithPath: currentWorkingPath)
archiveURL.appendPathComponent("test.zip")
guard let archive = Archive(url: archiveURL, accessMode: .read) else {
return
}
guard let entry = archive["file.txt"] else {
return
}
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("out.txt")
do {
try archive.extract(entry, to: destinationURL)
} catch {
print("Extracting entry from archive failed with error:\(error)")
}
您还可以使用基于闭包的 API 直接访问 entry
的内容.这允许您处理条目而无需先将其写入文件系统:
You can also directly access the contents of entry
by using the closure based API. This allows you to process the entry without writing it to the file system first:
try archive.extract(entry, consumer: { (data) in
print(data.count)
})
这篇关于Swift:解压文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!