Generally, there are two methods for file access. These two methods are mainly divided based on the file content. A file composed of text can be read and written using characters, while other types of files are usually stored in the form of bytecode (of course, we can also use bytecode to store text ).
In OC, The NSString class can directly call internal methods to read and write strings. Unlike java, I/O Stream classes are used for a series of encapsulation. In addition, OC text access is very simple. For example, you can use the following lines to write specific text files:
# Pragma writes data to the file using NSString: NSError * error = nil; NSMutableString * str = [[NSMutableString alloc] init]; for (int I = 0; I <10; I ++) {[str appendString: @ "Hello! Hello \ n "];} if ([str writeToFile: @"/tmp/my.txt "atomically: YES encoding: NSUTF8StringEncoding error: & error]) {NSLog (@ "success");} else {NSLog (@ "error: % @", [error localizedDescription]);}
Reading is also rare:
# Pragma reads data from a file using NSString: NSError * error = nil; NSString * str = [[NSString alloc] initWithContentsOfFile: @ "/tmp/my.txt" encoding: NSUTF8StringEncoding error: & error]; if (str) {NSLog (@ "content: % @", str);} else {NSLog (@ "error: % @", [error localizedDescription]);}
What then?
When using NSData, I was even more shocked to understand the unique simplicity of Objective-C, and obviously had great advantages in java/c ++, python/php is simple and clear.
There are several lines of code to read and write NSData files.
# Pragma uses NSData to access NSError * error = nil; NSData * data = [[NSData alloc] initWithContentsOfFile: @ "/tmp/my.txt"]; if ([data writeToFile: @ "/tmp/my2.txt" options: NSDataWritingAtomic error: & error]) {NSLog (@ "success");} else {NSLog (@ "error: % @", error );}