【问题标题】:How do I read a file from the filesystem in a Swift command line app?如何在 Swift 命令行应用程序中从文件系统中读取文件?
【发布时间】:2019-01-18 09:54:47
【问题描述】:

我刚刚开始学习 Swift,为了自学,我正在制作一个简单的命令行应用程序。它最终会连接到在线数据源,但最初我想从文件中加载数据。我看过各种关于在 Swift 中读取文件内容的指南,但它们似乎都不适合我。到目前为止,这是我的应用程序:

import Foundation

// Set the file path
let path = "/Users⁩/username/workspace⁩/⁨Swift⁩/sis⁩/sis/data.json⁩"

do {
    // Get the contents
    let contents = try String(contentsOfFile: path, encoding: .utf8)
    print(contents)
}
catch let error as NSError {
    print("Ooops! Something went wrong: \(error)")
}

运行它输出:

Ooops! Something went wrong: Error Domain=NSCocoaErrorDomain Code=260 "The file “data.json⁩” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users⁩/username/workspace⁩/⁨Swift⁩/sis⁩/sis/data.json⁩, NSUnderlyingError=0x100e19a50 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

但是在终端上:

$ ls -l /Users/username/workspace/Swift/sis/sis/data.json
-rwxrwxrwx@ 1 username  staff  165563 16 Jan 17:14 /Users/username/workspace/Swift/sis/sis/data.json

(是的,我稍微放宽了权限,以防万一出现问题)

我注意到的唯一一点异常(除了文件不存在的不准确断言之外)是,当我将路径从 XCode 输出复制并传递到 iTerm2 中时,它会在每个路径组件之间放置空格:

(粘贴为图像,因为复制它并将其粘贴回此表单似乎隐藏了空格 - 无论如何这可能无关紧要)

非常感谢任何帮助解决这个问题!

【问题讨论】:

  • 您的代码看起来正确,但您的let path = ... 行中确实有一些不可见的字符。删除并重新输入该行应该可以解决问题。
  • 您也可以print(Array(path.unicodeScalars))查看问题原因。

标签: swift command-line-interface


【解决方案1】:

我复制了您的代码,将sample json 文件下载到我的桌​​面,并将其重命名为 example_1.json(我在文件名中包含了一个空格)。

import Foundation

// Set the file path
let path = "/Users⁩/username/Desktop/example_ 1.json⁩"

do {
    // Get the contents
    let contents = try String(contentsOfFile: path, encoding: .utf8)
    print(contents)
}
catch let error as NSError {
    print("Ooops! Something went wrong: \(error)")
}

它成功打印了文件。当我将 contents 定义为 NSString 时,它也有效。

let contents = try NSString(contentsOfFile: path, 
                            encoding: String.Encoding.ascii.rawValue)

我正在使用 Swift 4.2.1

【讨论】:

  • 非常感谢您的尝试。我尝试在桌面上创建一个新文件并引用它,但该文件出现类似错误。我认为我的系统/环境有问题,但我不确定从哪里开始......
  • 我不确定这是否有帮助,但您使用的是哪个版本的 Swift?运行“swift -v”找出答案。
【解决方案2】:

如果您的命令行应用程序被沙盒化,您将无法读取。您可以做的是将此文件添加到您的项目中,并通过在身份检查器中查看文件的完整路径来设置文件路径。

let path = "/Users/snx/EmailReplacer/EmailReplacer/shared_domains_staging.json"
do {
    let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
    let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
    if let jsonResult = jsonResult as? Dictionary<String, AnyObject> {
        print(jsonResult)
    }
} catch {
    print(error)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多