使用ZIPFoundation,如何将文件添加到所需路径的存档?

时间:2017-09-19 14:44:59

标签: swift zip zipfoundation

我正在尝试使用ZIPFoundation lib将文件添加到Swift中的存档。

存档看起来像这样:

/ /folder1/ /folder2/ <-- Move file here.

目前使用它将我的文件添加到存档中,但我没有得到参数的逻辑:

public func addEntry(with path: String, relativeTo baseURL: URL)

创建Archive对象并使用addEntry()添加文件,有没有办法将文件添加到存档的根路径?

代码编辑:

internal func moveLicense(from licenseUrl: URL, to publicationUrl: URL) throws {
    guard let archive = Archive(url: publicationUrl, accessMode: .update) else  {
        return
    }
    // Create local folder to have the same path as in the archive.
    let fileManager = FileManager.default
    var urlMetaInf = licenseUrl.deletingLastPathComponent()

    urlMetaInf.appendPathComponent("META-INF", isDirectory: true)
    try fileManager.createDirectory(at: urlMetaInf, withIntermediateDirectories: true, attributes: nil)

    let uuu = URL(fileURLWithPath: urlMetaInf.path, isDirectory: true)
    // move license in the meta-inf folder.
    try fileManager.moveItem(at: licenseUrl, to: uuu.appendingPathComponent("license.lcpl"))
    // move dir
    print(uuu.lastPathComponent.appending("/license.lcpl"))
    print(uuu.deletingLastPathComponent())
    do {
    try archive.addEntry(with: uuu.lastPathComponent.appending("license.lcpl"), // Missing '/' before license
                         relativeTo: uuu.deletingLastPathComponent())
    } catch {
        print(error)
    }
}
// This is still testing code, don't mind the names :)

1 个答案:

答案 0 :(得分:1)

ZIP存档中的路径条目实际上不是像大多数现代文件系统那样的分层路径。它们或多或少只是标识符。通常,这些标识符用于存储指向原始文件系统上的条目的路径。

ZIPFoundation中的addEntry(with path: ...)方法只是上述用例的便捷方法 例如,假设我们要在物理文件系统上添加具有以下路径的文件中的条目:

/temp/x/fileA.txt

如果我们想使用相对路径来识别档案中的fileA.txt条目,我们可以使用:

archive.addEntry(with: "x/fileA.txt", relativeTo: URL(fileURLWithPath: "/temp/")

稍后,这将允许我们用以下内容查找条目:

archive["x/fileA.txt"]

如果我们不想保留除文件名之外的任何路径信息,我们可以使用:

let url = URL(fileURLWithPath: "/temp/x/fileA.txt"
archive.addEntry(with: url.lastPathComponent, relativeTo: url.deletingLastPathComponent())

这样我们就可以使用文件名查找条目了:

archive["fileA.txt"]

如果您需要更多地控制路径/文件名,可以使用closure based API in ZIPFoundation。如果您的条目内容来自内存,或者您想要从没有公共父目录的文件中添加条目,这将非常有用。