2014-09-02 89 views
2

我嘗試在Swift中打開文件。爲此,我創建了文件路徑。它不起作用。無法在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!") 
} 

有什麼不對?

+0

問題是該文件不屬於「包」。如果你只需要使用['NSFileManager'](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html)(或'NSURL')對資源路徑的引用)。 – Alladinian 2014-09-02 15:24:58

回答

6

在使用雨燕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