本文介绍了无法在Swift中建立文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试在Swift中打开文件.为此,我创建了文件路径.它不起作用.
I try to open the file in Swift. For it I create the file path. It doesn't work.
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()
的路径实际上指向:
When using Swift REPL, the NSBundle.mainBundle()
's path actually points to:
/Applications/Xcode6-Beta6.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources
您可能必须使用 NSFileManager 代替:
You may have to use NSFileManager instead:
let manager = NSFileManager.defaultManager()
if manager.fileExistsAtPath("/Users/tsypa/a.txt") {
// file exists, read
} else {
// file doesn't exist
}
注意:实际上,您可以自动在路径中扩展代字号,以避免对完整的用户主路径进行硬编码:
Note: You can actually automatically expand tilde in the path to avoid hardcoding the full user's home path:
"~/a.txt".stringByExpandingTildeInPath // prints /Users/<your user>/a.txt
这篇关于无法在Swift中建立文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!