将 字符串 写入文件
var str = "hello world !!!"
str.writeToFile("/Users/huaijie/hellotest.txt", atomically: false, encoding: NSUTF8StringEncoding, error: nil)
从文件中读取内容
let content = String(contentsOfFile: "/Users/huaijie/hellotest.txt", encoding: NSUTF8StringEncoding, error: nil)
print(content!)
从文件中读取二进制数据
let mydata = NSData(contentsOfFile: "/Users/huaijie/hellotest.txt");
let nsdata = NSString(data: mydata!, encoding: NSUTF8StringEncoding)
print(nsdata!)
判断文件是否存在
var bool = NSFileManager().fileExistsAtPath("/Users/huaijie/hellotest.txt")
println(bool)
查找文件
var path = NSBundle.mainBundle().pathForResource("test", ofType: "txt")
println(path)
根据动态用户名查找文件
if let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]{
let path = dirs[0].stringByAppendingPathComponent("file.txt")
println(path)
}
在Mac上打开文件选择对话框
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = true
openPanel.beginWithCompletionHandler{(result)-> Void in
if result == NSFileHandlingPanelOKButton{
print(openPanel.URL)
}
}