将数据写入文件
将NSString对象写入文件
//讲NSString对象写入文件
NSMutableString *str = [[NSMutableString alloc]init];
for (int i = 0 ; i<10; i++) {
[str appendString:@"Aaron is cool!\n"];
[str writeToFile:@"/tmp/cool.txt" atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"done writing /tmp/cool.txt");
}
//声明NSMutableString对象和NSError对象
NSMutableString *str = [[NSMutableString
NSError *error;
//将NSError指针通过引用传入writeToFile:atomically:encoding:error方法
BOOL success = [str writeToFile:@"/tmp/sddd/cool.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (success) {
NSLog(@"done writing /tmp/sddd/cool.txt");
} else {
NSLog(@"Error writing /tmp/sddd/cool.txt failed:%@",[error localizedDescription]);
}
注:
(方法声明中的双星号)
- 双星号代表相应的参数是一个地址,它存放了指向 NSError实例的指针。
- 如果某个方法的参数包含一个要通过引用的NSError指针,那么这个方法的返回值就应该表明(执行方法时)是否有错误发生
通过NSString读取文件
//通过NSString读取文件
NSError *error1;
NSString *str1 = [[NSString alloc] initWithContentsOfFile:@"/etc/resolv.conf" encoding:NSASCIIStringEncoding error:&error1];
if (!str1) {
NSLog(@"read failed: %@",[error1 localizedDescription]);
} else {
NSLog(@"resolv.conf looks like this: %@",str1);
}
将NSData对象所保存到数据写入文件,从文件读取数据并存入NSData对象
NSData对象“代表”内存中的某块缓冲区,可以保存相应字节数的数据。
下面代码任务是下载百度首页的logo图片,并将下载的数据保存在一个NSData实例中,然后要求该实例将其保存的二进制数据写入文件。
//声明url
NSURL *url = [NSURL URLWithString:@"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error = nil;
//声明NSData对象
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:&error];
if (!data) {
NSLog(@"fetch failed: %@",[error localizedDescription]);
return 1;
}
NSLog(@"The file is %lu bytes",(unsigned long)[data length]);
//把NSData对象写入到文件中,NSDataWritingAtomicb表示对象会先将数据写入临时文件,成功后再移动至指定文件
BOOL written = [data writeToFile:@"/tmp/bd_logo1_31bdc765.png" options:NSDataWritingAtomic error:&error];
if (!written) {
NSLog(@"write failed: %@", [error localizedDescription]);
}
NSLog(@"success!");
//从文件中读取数据并存入NSdata对象中
NSData *readData = [NSData dataWithContentsOfFile:@"/tmp/bd_logo1_31bdc765.png"];
NSLog(@"The file read from the disk has %lu bytes",(unsigned long)[readData length]);
寻找特别目录(路径)
NSArray *desktops = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopPath = desktops[0];