【问题标题】:Why would String(contentsOfFile) fail even though the file exists?即使文件存在,为什么 String(contentsOfFile) 会失败?
【发布时间】:2016-04-13 03:27:25
【问题描述】:

在下面的代码中,我试图访问位于我的主目录中的文件0.txt。主目录的路径保存在一个字符串中,并在调用时附加名称 0.txt0 是一个引用计数器,它将在程序运行时更改值。为了这个问题,我会将其称为0)。

func loadfile(counter: Int) -> String {     // counter here is assumed to be "0"
    var contents = String()
    var defaultpath = ("~/" as NSString).stringByExpandingTildeInPath as String
    do {
        contents = try String(contentsOfFile: defaultpath.stringByAppendingString(String("\(counter).txt")))
        return contents
    } catch {
        print("For some reason, the file couldn't be accessed.")
        return "failed"
    }
}

但是,每次运行此代码块时,返回值都是failed 并打印For some reason, the file couldn't be accessed 行,即使~/0.txt 存在。有谁知道为什么会发生这种异常行为,如果是,我应该如何解决这个问题??

附带问题:有没有办法将 try-catch 块产生的错误打印到标准输出?

【问题讨论】:

    标签: string swift file-io


    【解决方案1】:

    您需要在文件名中添加分隔符:

    contents = try String(contentsOfFile: defaultpath.stringByAppendingString(String("/\(counter).txt")))
    

    注意文件名开头的正斜杠。 defaultPath 不以斜线结尾。

    【讨论】:

    • gasp 我怎么会错过那个斜杠...谢谢。你有没有机会知道我如何打印生成的错误?
    • 这应该是一个单独的问题。但这里有一个来自操场的工作示例:do { let str = try NSString(contentsOfFile: "Foo.bar", encoding: NSUTF8StringEncoding) } catch let error as NSError { print(error.localizedDescription) }
    猜你喜欢
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    • 2014-11-06
    • 2012-08-21
    相关资源
    最近更新 更多