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

前端之家收集整理的这篇文章主要介绍了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 */}
}
原文链接:https://www.f2er.com/swift/321692.html

猜你在找的Swift相关文章