首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用ZIPFoundation将文件添加到所需路径的存档中?

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

Stack Overflow用户
提问于 2017-09-19 14:44:59
回答 1查看 1.1K关注 0票数 1

我试图使用ZIPFoundation库向Swift中的归档文件添加一个文件。

档案文件如下所示:

代码语言:javascript
复制
/
/folder1/
/folder2/ <-- Move file here.

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

代码语言:javascript
复制
public func addEntry(with path: String, relativeTo baseURL: URL)

创建一个Archive对象并使用addEntry()添加文件,是否有一种方法不只是将文件添加到归档的根路径?

代码编辑:

代码语言:javascript
复制
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 :)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-19 15:41:25

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

addEntry(with path: ...)方法在ZIPFoundation中只是一个方便的方法,上面的用例。

例如,假设我们希望从一个在物理文件系统上具有以下路径的文件中添加一个条目:

代码语言:javascript
复制
/temp/x/fileA.txt

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

代码语言:javascript
复制
archive.addEntry(with: "x/fileA.txt", relativeTo: URL(fileURLWithPath: "/temp/")

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

代码语言:javascript
复制
archive["x/fileA.txt"]

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

代码语言:javascript
复制
let url = URL(fileURLWithPath: "/temp/x/fileA.txt"
archive.addEntry(with: url.lastPathComponent, relativeTo: url.deletingLastPathComponent())

这将允许我们只使用文件名查找条目:

代码语言:javascript
复制
archive["fileA.txt"]

如果需要对路径/文件名进行更多控制,可以使用ZIPFoundation中基于闭包的API。如果条目内容来自内存,或者希望从没有公共父目录的文件中添加条目,则这一点尤其有用。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46303453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档