如何使用操场在Swift中读写数据到文本文件? [英] How to Read and Write data to a text file in Swift using playground?

查看:243
本文介绍了如何使用操场在Swift中读写数据到文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过这些SO链接的答案

1。在Swift中逐行读取文件/网址

2。从文本文件中读取和写入数据



链接2为我提供了解决方案,但问题是目录 。它是默认的当前项目的文档目录。

所以,如果我想从/ Users / Prem / Desktop / File.txt

如何使用自定义目录读取和写入文本文件中的数据?

$

b
$ b

  let dirs:[String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask,true)as? [String] 

if((dirs)!= nil){
var dir = dirs![0]; //文件目录
// println(dir)

// dir =/ Users / Prem / Desktop---->如果我给这个路径,它不会创建文件

// dir中的当前值
// dir ----> /Users/Prem/Library/Containers/com.apple.dt.playground.stub.OSX.FileIO-2159807F-CC21-4545-AC34-AD9F9898796B/Data/Documents

let path = dir .stringByAppendingPathComponent( file.txt的);
println(path)
let text =Rondom Text

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

解决方案

经过几天的尝试,很明显,

如果我们尝试在操场上进行文件处理,我们就不能访问除了项目自包含的目录之外的东西。因为它被沙盒化了,所以我们可以访问任何一个目录并执行读/写操作。

信用:@robMayoff


I read through these SO links for the answer

1. Read a file/URL line-by-line in Swift

2. Read and write data from text file

Link 2 Provided me the solution but the problem is directory. It is by default Document directory of the current project.

So if i want to read a file from "/Users/Prem/Desktop/File.txt", what modification i should make to that code?

How to work with custom directory to read and write data in a text file?

let dirs : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

if ((dirs) != nil) {
    var dir = dirs![0]; //documents directory
    //println(dir)

    //dir = "/Users/Prem/Desktop"  ----> If i give this path, its not creating the file

    //Current Value in dir
    //dir ----> "/Users/Prem/Library/Containers/com.apple.dt.playground.stub.OSX.FileIO-2159807F-CC21-4545-AC34-AD9F9898796B/Data/Documents"

    let path = dir.stringByAppendingPathComponent("File.txt");
    println(path)
    let text = "Rondom Text"

    //writing
    text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
}

解决方案

After trying out for couple of days it is clear that,

We cannot access other than the project's self contained directories, if we try 'file handling' in playground. Because it is sandboxed

But from an xcode project, we can access any directory and perform read/write operations.

credits: @robMayoff

这篇关于如何使用操场在Swift中读写数据到文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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