一般的,文件存取都有两种方式,这两种方式主要是根据文件的内容来划分的。对于由文字组成的文件可以利用字符读写的方式,而其他类型的文件通常用字节码的形式来存的(当然,我们亦可以用字节码来存文字)。
在OC中NSString类直接能够调用内部的方法去读区、写入string.而不像java得用IO流类进行一系列的封装。而且OC的文本访问是很简单的,比如用下面的几行就能对特定的文本文件写入:
#pragma 使用NSString写入文件中:
NSError *error = nil;
NSMutableString *str = [[NSMutableString alloc] init];
for(int i=0;i<10;i++){
[str appendString:@"你好!hello\n"];
}
if([str writeToFile:@"/tmp/my.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error]){
NSLog(@"success");
}
else{
NSLog(@"error:%@",[error localizedDescription]);
}
而读取也是很少的:
#pragma 使用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]);
}
然后呢?
当使用NSData的时候,我更加震惊地体会到了Objective-C的独特简便性,对于java/c/c++显然有挺大的优势,而对于python/php来说也是简单明确的。
一下就是几行代码实现使用NSData的文件读写。
#pragma 使用NSData存取
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);
}