简体   繁体   English

无法在Swift中建立文件的路径

[英]Can not make path to the file in Swift

I try to open the file in Swift. 我尝试在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:~ $ 

The script: 剧本:

#!/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!")
}

What's wrong? 怎么了?

When using Swift REPL, the NSBundle.mainBundle() 's path actually points to: 使用Swift REPL时, NSBundle.mainBundle()的路径实际上指向:

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

You may have to use NSFileManager instead: 您可能必须改用NSFileManager

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM