如何使用游乐场在Swift中读取和写入数据到文本文件?

如何使用游乐场在Swift中读取和写入数据到文本文件?,第1张

概述参见英文答案 > Swift Playground – Files are not readable                                    2个 我通读了这些SO链接以获得答案 1. Read a file/URL line-by-line in Swift 2. Read and write data from text file 链接2为我提供了解决方案,但问题 参见英文答案 > Swift Playground – Files are not readable                                    2个
我通读了这些SO链接以获得答案

@L_502_1@

2. Read and write data from text file

链接2为我提供了解决方案,但问题是目录.默认情况下,它是当前项目的document目录.

因此,如果我想从“/Users/Prem/Desktop/file.txt”中读取文件,我应该对该代码进行哪些修改?

如何使用自定义目录在文本文件中读写数据?

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,error: nil)}
解决方法 经过几天试用后很明显,

如果我们在游乐场尝试“文件处理”,我们就无法访问项目的自包含目录.因为它是沙盒

但是从xcode项目中,我们可以访问任何目录并执行读/写 *** 作.

学分:@robMayoff

总结

以上是内存溢出为你收集整理的如何使用游乐场在Swift中读取和写入数据到文本文件?全部内容,希望文章能够帮你解决如何使用游乐场在Swift中读取和写入数据到文本文件?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1019560.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存