我正在尝试用快速语言创建一个txt文件。 我可以这样做吗?
我试图检查文件是否存在:4
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath("history.txt") {
print("File exists")
} else {
print("File not found")
//If the file doesn't exist I want to create it here
}
答案 0 :(得分:1)
请你试试这个,
let someDummyTextForTextFile = "Hi there I am the contents of text file"
let data:NSData = someDummyTextForTextFile.dataUsingEncoding(NSUTF8StringEncoding)!
let fileManage = NSFileManager.defaultManager()
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
data.writeToFile("\(dir)/myFile.txt", atomically: true)
}
这将在文档目录中创建一个文本文件。或者只是试试这个,
if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
do {
try someDummyTextForTextFile.writeToFile("\(dir)/myFile.txt", atomically: true, encoding: NSUTF8StringEncoding)
}
catch _ {
print("something went wrong")
}
}