我尝试在 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
你可能需要使用NS文件管理器 https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/index.html反而:
let manager = NSFileManager.defaultManager()
if manager.fileExistsAtPath("/Users/tsypa/a.txt") {
// file exists, read
} else {
// file doesn't exist
}
Note:实际上,您可以自动扩展路径中的波形符,以避免对完整用户的主路径进行硬编码:
"~/a.txt".stringByExpandingTildeInPath // prints /Users/<your user>/a.txt
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)