在iPhone的开发中免不了要从网络下载文保存到本地,iPhone的文件系统跟Mac很像,但也有些区别,它使用了一种sandbox机制,你只能查看自己程序目录下的内容,不能访问其它程序的目录,
当我们的程序运行时,系统给我们的应用程序预设了几个目录,分别是Document,应用程序目录,Library(Caches和Preferences子目录),tmp目录,如下图。
要对这些文件夹进行操作,首先当然是要取得这些目录的绝对路径,iOS给我们提供了几个函数来取得这些路径。
基本函数
// 获取家目录路径
NSString *homeDir = NSHomeDirectory();
// 获取Documents目录路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
// 获取Caches目录路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
// 获取tmp目录路径
NSString *tmpDir = NSTemporaryDirectory();
// 获取程序包中一个图片资源(apple.png)路径
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"];
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
实际操作
1.在Document目录创建一个目录,并在该目录中创建一个文本文件
// 获取Document目录
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
// 创建test目录
NSString *newDirectoryPath = [docDir stringByAppendingPathComponent:@"test"];
if (![[NSFileManager defaultManager] fileExistsAtPath:newDirectoryPath]) {
[[NSFileManager defaultManager] createDirectoryAtPath:newDirectoryPath withIntermediateDirectories:NO attributes:nil error:&error];
// 数据写入文本文件
NSString *fileName = [NSString stringWithFormat:@"%@/hello.txt", newDirectoryPath];
NSString *content = @"死了都要爱";
[content writeToFile:fileName atomically:NO encoding:NSUTF8StringEncoding error:&error];
2.从Document读取一个文本文件
// 获取Document目录
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
// 读取txt文件
NSString *fileName = [NSString stringWithFormat:@"%@/test/hello.txt", docDir];
NSLog(@"fileName: %@", fileName);
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:&error];
NSLog(@"content: %@", content);
3.从网上下载一张图片保存到Document目录
// 获取Document目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com.hk/images/nav_logo104.png"]];
NSString *fileName = [NSString stringWithFormat:@"%@/nav_logo104.png", docDir];
[data writeToFile:fileName atomically:NO];
4.从Document目录中读取图片文件显示到UIWebView中
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/nav_logo104.png", docDir];
NSString *image = [NSString stringWithFormat:@"<img src=\"file://%@\" />", fileName];
[webView loadHTMLString:image baseURL:nil];
运行效果