Macos 无法在Swift中创建文件的路径

Macos 无法在Swift中创建文件的路径,macos,swift,nsbundle,Macos,Swift,Nsbundle,我试着用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",

我试着用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!")
}

怎么了?

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

/Applications/Xcode6-Beta6.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources
您可能必须改用:


注意:实际上,您可以在路径中自动展开平铺,以避免硬编码完整用户的主路径:

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

问题在于该文件不属于“bundle”。如果只需要对资源路径的引用,请改用(或
NSURL
)。
"~/a.txt".stringByExpandingTildeInPath // prints /Users/<your user>/a.txt