新建一个demo项目缓存
在 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中调用以下代码app
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *documentDirectory = [documentDirectories firstObject]; NSLog(@"documentDirectory = %@",documentDirectory);
输出的路径,在finder中能够前往文件夹打开spa
能够看到以下的目录结构.net
Documents 目录是保存数据,备份或者同步也是这个目录
Library/Caches app产生的数据会保存在这里,用来记住每次运行的数据,可是不会被同步code
Library/Preferences NSUserDefault类操做的数据blog
temp/ 不会备份,可是不须要的时候仍是能清处理,NSTemporaryDirectory图片
由于应用是在沙箱(sandbox)中的,在文件读写权限上受到限制,只能在几个目录下读写文件:资源
constructing a file path开发
- (NSString *)itemArchivePath{ NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *documentDirectory = [documentDirectories firstObject]; return [documentDirectory stringByAppendingPathComponent:@"items.archive"]; }
- (BOOL)saveChanges{ NSString *path = [self itemArchivePath]; return [NSKeyedArchiver archiveRootObject:self.privateItems toFile:path]; }
保存的结果是文件系统中会多出一个items.archive的文件rem
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
保存图片到沙盒路径
读取沙盒路径下的文件
NSString *myFilePath = [[NSBundle mainBundle] pathForResource:@"f" ofType:@"txt"]; NSString *myFileContent=[NSString stringWithContentsOfFile:myFilePath encoding:NSUTF8StringEncoding error:nil]; NSLog(@"bundel file path: %@ \nfile content:%@",myFilePath,myFileContent);
NSFileManager* fm=[NSFileManager defaultManager]; if(![fm fileExistsAtPath:[self dataFilePath]]){ //下面是对该文件进行制定路径的保存 [fm createDirectoryAtPath:[self dataFilePath] withIntermediateDirectories:YES attributes:nil error:nil]; //取得一个目录下得全部文件名 NSArray *files = [fm subpathsAtPath: [self dataFilePath] ]; //读取某个文件 NSData *data = [fm contentsAtPath:[self dataFilePath]]; //或者 NSData *data2 = [NSData dataWithContentsOfFile:[self dataFilePath]]; }
http://blog.csdn.net/xingxing513234072/article/details/24184917
复习问题
1. 如何获取沙盒中的document路径?
2,开发者能够直接进行读写操做的路径有哪些?缓存型的数据能够放在哪里?须要持久化保存的数据应该放在哪里?
3,在沙盒中document路径下创建一个ScreenShotImages的文件夹,并往其中保存屏幕截图的内容。
4,读取沙盒中document路径下的全部文件或者文件夹,并打印文件或者文件夹的名称
5,请写出删除指定目录document文件夹下log.txt 的代码
6,删除document文件夹下ScreenShotImages文件夹的代码