iOS沙盒分为以下几个文件夹
1. Document: 程序创建或者应用浏览产生的文件数据
2. Library: 程序的默认设置或者状态信息
3. temp: 临时文件夹,不需要持久化
文件操作API
1. 获取app沙盒中根目录
NSHomeDirectory()
2. 获取app沙盒中Document文件夹
NSString *homePath = NSHomeDirectory();
3. 获取app沙盒中Library文件夹:NSHomeDirectory()
NSArray *searchPatch = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *path = [searchPatch lastObject]
4. 获取app沙盒中temp文件夹:NSHomeDirectory()
NSArray *libraryPatch = NSSearchPathForDirectoriesInDomains( NSLibraryDirectory, NSUserDomainMask, YES);
NSString *path = [searchPatch lastObject]
5. 字符串URL解析为各个模块
NSString *patch = @"/data/driver/test.png";
NSArray *component = [patch pathComponents];
[patch stringByDeletingLastPathComponent];
[patch stringByAppendingPathComponent:@"test.png"]
6. 创建文件夹
BOOL ret = [fileManager createDirectoryAtPath:testPatch withIntermediateDirectories:NO attributes:nil error:nil];
7. 创建文件
BOOL ret = [content writeToFile:testPatch atomically:YES encoding:NSUTF8StringEncoding error:nil];
8. 检测文件是否存在
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePatch]) {
NSLog(@"文件已存在");
} else {
NSLog(@"文件不存在");
}
9. 追加文件
NSArray *docPatch = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *testPatch = [[docPatch lastObject] stringByAppendingString:@"test/test.txt"];
NSFileHandle *fileManager = [NSFileHandle fileHandleForUpdatingAtPath:testPatch];
[fileManager seekToEndOfFile];
NSString *str = @"这是追加的内容";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileManager writeData:data];
[fileManager closeFile];
10. 删除文件
BOOL ret1 = [fileManager removeItemAtPath:testPatch error:nil];
网友评论