1.NSString读写文件
NSString *helloText=@"您好啊!";NSError *error;if ([helloText writeToFile:@"/tmp/test.txt" atomically:true encoding:NSUTF8StringEncoding error:&error]){NSLog(@"writeToFile success");}else{NSLog(@"writeToFile failed:%@",[error localizedDescription]);}NSString *readText=[[NSString alloc] initWithContentsOfFile:@"/tmp/test.txt" encoding:NSUTF8StringEncoding error:NULL];NSLog(@"%@",readText);
2.NSData读写文件
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];NSURLRequest *request=[NSURLRequest requestWithURL:url];NSError *error;NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:&error];if (!data){NSLog(@"fetch failed with error %@",[error localizedDescription]);}else{if ([data writeToFile:@"/tmp/test1.txt"options:NSDataWritingAtomicerror:&error]){NSLog(@"write success");}else{NSLog(@"write failed with error %@",[error localizedDescription]);}}NSData *readData=[NSData dataWithContentsOfFile:@"/tmp/test1.txt"];NSLog(@"file size is %ld",[readData length]);