【问题标题】:Can not make path to the file in Swift无法在 Swift 中创建文件路径
【发布时间】:2014-09-02 15:18:56
【问题描述】:

我尝试在 Swift 中打开文件。为此,我创建了文件路径。它不起作用。

maaaacy:~ $ pwd
/Users/tsypa
maaaacy:~ $ cat a.txt
test
maaaacy:~ $ ./a.swift 
nil!
maaaacy:~ $ 

脚本:

#!/usr/bin/xcrun swift 

import Foundation

var filePath = NSBundle.mainBundle().pathForResource("a", ofType: "txt", inDirectory: "/Users/tsypa")
if let file = filePath {
        println("file path \(file)")
        // reading content of the file will be here
} else {
        println("nil!")
}

怎么了?

【问题讨论】:

  • 问题是该文件不属于“捆绑包”。请改用NSFileManager(或NSURL,如果您只需要引用资源的路径)。

标签: macos swift nsbundle


【解决方案1】:

使用 Swift REPL 时,NSBundle.mainBundle() 的路径实际上指向:

/Applications/Xcode6-Beta6.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources

您可能必须改用NSFileManager

let manager = NSFileManager.defaultManager()

if manager.fileExistsAtPath("/Users/tsypa/a.txt") {
    // file exists, read
} else {
    // file doesn't exist
}

注意:您实际上可以在路径中自动扩展波浪号以避免硬编码完整用户的主路径:

"~/a.txt".stringByExpandingTildeInPath // prints /Users/<your user>/a.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    相关资源
    最近更新 更多