file-io – 从文本文件读取和写入数据

我需要读/写一个文本文件的数据,但我还没有能够弄清楚如何。

我在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 */}
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...