为什么即使文件存在,String(contentsOfFile)也会失败?

时间:2016-04-13 03:27:25

标签: string swift file-io

在下面的代码中,我试图访问位于我的主目录中的文件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块生成的错误打印到stdout?

1 个答案:

答案 0 :(得分:1)

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

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

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