读取和写入文本文件中的数据 [英] Read and write data from text file

查看:108
本文介绍了读取和写入文本文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从文本文件中读取/写入数据,但是我一直无法弄清楚。



我发现这个示例代码Swift的iBook,但我仍然不知道如何写或读数据。

  import Cocoa 

class DataImporter
{
/ *
DataImporter是一个从外部文件导入数据的类。
假设这个班级需要花费很少的时间进行初始化。
* /
var fileName =data.txt
// DataImporter类将在这里提供数据导入功能

$ b $ class DataManager

@lazy var importer = DataImporter()
var data = String []()
// DataManager类在这里提供数据管理功能


让manager = DataManager()
manager.data + =某些数据
manager.data + =更多数据
//导入器的DataImporter实例属性尚未创建

println(manager.importer.fileName)
//导入器属性的DataImporter实例现在已创建
//打印数据。 txt



var str =Swift语言中的Hello World。

$ b $对于读写,你应该使用一个可写的位置,例如文档目录下面的代码展示了如何读写一个简单的字符串。能够

Swift 1.x

如果让dirs:[String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask,true)作为参数,则file =file.txt

[String] {
let dir = dirs [0] // documents directory
let path = dir.stringByAppendingPathComponent(file);
let text =some text

//写入
text.writeToFile(path,atomically:false,encoding:NSUTF8StringEncoding,error:nil);
$ b //阅读
让text2 = String(contentsOfFile:path,encoding:NSUTF8StringEncoding,error:nil)
}
pre>

Swift 2.2

  let file =file.txt//这是文件。我们将写入和读取

让text =一些文本//只是一个文本

如果让dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath:dir).URLByAppendingPathComponent(file)

//写入
do {
try text.writeToURL(path ,原子:false,编码:NSUTF8StringEncoding)
}
catch {/ *错误处理在这里* /}

//读$ b $ do {
let text2 = try NSString(contentsOfURL:path,encoding:NSUTF8StringEncoding)
}
catch {/ *错误处理在这里* /}
}
pre>

Swift 3.x和Swift 4.0

  let file =file.txt//这是文件。我们将写入和读取它

让text =一些文本//只是一个文本

如果让dir = FileManager.default.urls(for:.documentDirectory ,在:.userDomainMask).first {

let fileURL = dir.appendingPathComponent(file)

//写
do {
尝试文字。写(到:fileURL,原子:false,编码:.utf8)
}
catch {/ *错误处理在这里* /}

//读
{
让text2 = try String(contentsOf:fileURL,encoding:.utf8)
}
catch {/ *错误处理在这里* /}
}


I need to read and write data to/from a text file, but I haven't been able to figure out how.

I found this sample code in the Swift's iBook, but I still don't know how to write or read data.

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."

解决方案

For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground.

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, encoding: NSUTF8StringEncoding, 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, NSSearchPathDomainMask.AllDomainsMask, true).first {
    let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)

    //writing
    do {
        try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
    }
    catch {/* error handling here */}

    //reading
    do {
        let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
    }
    catch {/* error handling here */}
}

Swift 3.x and Swift 4.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 fileURL = dir.appendingPathComponent(file)

    //writing
    do {
        try text.write(to: fileURL, atomically: false, encoding: .utf8)
    }
    catch {/* error handling here */}

    //reading
    do {
        let text2 = try String(contentsOf: fileURL, encoding: .utf8)
    }
    catch {/* error handling here */}
}

这篇关于读取和写入文本文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆