我在Swift的iBook中找到了这个示例代码,但我还是不知道如何写或读数据。
import Cocoaclass 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 itlet text = "some text" //just a textif 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 itlet text = "some text" //just a textif 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 */}}总结
以上是内存溢出为你收集整理的file-io – 从文本文件读取和写入数据全部内容,希望文章能够帮你解决file-io – 从文本文件读取和写入数据所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)