问题
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)
}
回答1:
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
来源:https://stackoverflow.com/questions/28463453/how-to-read-and-write-data-to-a-text-file-in-swift-using-playground