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

时间:2023-01-23 16:47:30

This question already has an answer here:

这个问题在这里已有答案:

I read through these SO links for the answer

我通读了这些SO链接以获得答案

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

1.在Swift中逐行读取文件/ URL

2. Read and write data from text file

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

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

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

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

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

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)
}

1 个解决方案

#1


7  

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.

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

credits: @robMayoff

#1


7  

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.

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

credits: @robMayoff