Created
June 7, 2014 10:33
-
-
Save frozzare/d4a9bbeb39e5425e7c26 to your computer and use it in GitHub Desktop.
Example of how to create a file class with read, write and exists functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class File { | |
class func exists (path: String) -> Bool { | |
return NSFileManager().fileExistsAtPath(path) | |
} | |
class func read (path: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> String? { | |
if File.exists(path) { | |
return String.stringWithContentsOfFile(path, encoding: encoding, error: nil)! | |
} | |
return nil | |
} | |
class func write (path: String, content: String, encoding: NSStringEncoding = NSUTF8StringEncoding) -> Bool { | |
return content.writeToFile(path, atomically: true, encoding: encoding, error: nil) | |
} | |
} | |
let read : String? = File.read("/path/to/file.txt") | |
println(read) | |
let write : Bool = File.write("/path/to/file2.txt", content: "String to write") | |
println(write) |
And how can I create a new file?
String.stringWithContentsOfFile() has been deprecated. You need to use:
String(contentsOfFile: path, encoding: encoding, error: nil)
Thank you so much!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Friends,
I add something new fades previous data.
I would hope that when you added new data is added to the old data.
So you'd already added protection.
example:
File.write("/path/to/file2.txt", content: "String to write"
File.write("/path/to/file2.txt", content: "Hello world"
File.read("/path/to/file.txt") ---- > print out ->"Hello world"
"String to write" deleted
File.read("/path/to/file.txt") ---> print out -> "String to write
Hello world" must be
How do I do this?