[数据存储之三]文件的读取

- (void)viewDidLoad {
    [super viewDidLoad];
    /*写入文件,有的话替换,没有的话新建*/
    NSArray* paths =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSAllDomainsMask, true);
    if ([paths count] == 0) return;
    NSURL* url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/data.txt",paths[0]]];
    NSMutableData* data = [[NSMutableData alloc] init];
    NSString* appendText = @"hello world liyanq~~";
    [data appendData:[appendText dataUsingEncoding:NSUTF8StringEncoding
                              allowLossyConversion:YES]];
    [data writeToFile:[url path] atomically:YES];
  
    
    /*读取文件:第一种*/
    NSData* dataOpen = [NSData dataWithContentsOfFile:[url path]];
    NSString* str = [NSString stringWithUTF8String:[dataOpen bytes]];
    NSLog(@"%@",str);
    
    /*读取文件:第二种*/
    NSString* str2 = [NSString stringWithContentsOfFile:[url path]
                                               encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",str2);
    /*读取文件:第三种*/
    NSString* str3 = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",str3);
    
}
关于目录找的参数,请参考:http://blog.sina.com.cn/s/blog_923fdd9b01014fun.html

你可能感兴趣的:(文件,数据存储)