代码之家  ›  专栏  ›  技术社区  ›  user1585121

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

  •  1
  • user1585121  · 技术社区  · 8 年前

    我正在尝试使用ZIPFoundation库将文件添加到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 回复  |  直到 5 年前
        1
  •  3
  •   Thomas Zoechling    8 年前

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

    这个 addEntry(with path: ...) ZIPFoundation中的方法只是上述用例的一种方便方法。

    /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