我需要读/写一个文本文件的数据,但我还没有能够弄清楚如何。
我在Swift的iBook中找到了这个示例代码,但我还是不知道如何写或读数据。
import Cocoa class DataImporter { /* DataImporter is a class to import data from an external file. The class is assumed to take a non-trivial amount of time to initialize. */ var fileName = "data.txt" // the DataImporter class would provide data importing functionality here } class DataManager { @lazy var importer = DataImporter() var data = String[]() // the DataManager class would provide data management functionality here } let manager = DataManager() manager.data += "Some data" manager.data += "Some more data" // the DataImporter instance for the importer property has not yet been created” println(manager.importer.fileName) // the DataImporter instance for the importer property has now been created // prints "data.txt” var str = "Hello World in Swift Language."
对于读写,应该使用可写的位置,例如文档目录。以下代码显示如何读取和写入一个简单的字符串。你可以在操场上测试它。
Swift 1.x
let file = "file.txt" if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask,true) as? [String] { let dir = dirs[0] //documents directory let path = dir.stringByAppendingPathComponent(file); let text = "some text" //writing text.writeToFile(path,atomically: false,encoding: NSUTF8StringEncoding,error: nil); //reading let text2 = String(contentsOfFile: path,error: nil) }
Swift 2.2
let file = "file.txt" //this is the file. we will write to and read from it let text = "some text" //just a text if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,true).first { let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file) //writing do { try text.writeToURL(path,encoding: NSUTF8StringEncoding) } catch {/* error handling here */} //reading do { let text2 = try NSString(contentsOfURL: path,encoding: NSUTF8StringEncoding) } catch {/* error handling here */} }
Swift 3.0
let file = "file.txt" //this is the file. we will write to and read from it let text = "some text" //just a text if let dir = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first { let path = dir.appendingPathComponent(file) //writing do { try text.write(to: path,encoding: String.Encoding.utf8) } catch {/* error handling here */} //reading do { let text2 = try String(contentsOf: path,encoding: String.Encoding.utf8) } catch {/* error handling here */} }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。