I'm searching Swift file input/output operations for a short presentations on my university next week. I really didn't find much about it.
Here are the Operations I found:
let location = "/Users/test/test.txt"
var str = "Hello, playground"
//write
str.writeToFile( location, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
//read
let filecontent = String(contentsOfFile: location, encoding: NSUTF8StringEncoding, error: nil)
//binary read
let test = NSData(contentsOfFile: location)
//if file exists
NSFileManager().fileExistsAtPath(location)
//find Files in the App Bundle with suffix test and prefix txt
var path= NSBundle.mainBundle().pathForResource("test", ofType: "txt")
//path for dynamic user names
if let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
let path = dirs[0].stringByAppendingPathComponent( "file.txt")
//printout: /Users/test/Documents/file.txt
Is there an Operations with which I can read single characters?
Can I append Text to a File?
Can I write/read only String?
Is there any other File Operations, there I need to know?
Is there an Operations with which I can read single characters?
Swift code can use any of the usual frameworks (Foundation, Cocoa, Cocoa Touch, etc.), and that alone gives you a great many ways to read and write files, usually at a higher level than a character at a time. If you want lower level file I/O you can use NSInputStream
and NSOutputStream
as Martin R. suggests, or you can use NSData
.
Of course, you can also use all the usual C stdio
functions if you really want to get down and dirty with your files. But when you're operating on objects it doesn't usually make sense to work at a low level like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With