获取应用沙盒根路径
NSString *dirHome = NSHomeDirectory();
获取 Documents 目录文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths lastObject];
获取 Library 目录路径
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libraryDirectofry = [paths2 lastObject];
获取 Tmp 目录路径
NSString *tmpDirectory = NSTemporaryDirectory();
创建文件夹
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testDirectory = [documentsDirectory stringByAppendingString:@"test"];
BOOL res = [fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
if (res) {
NSLog(@"创建文件夹成功");
} else {
NSLog(@"创建文件夹失败");
}
创建文件
NSData *data = [NSData dataWithContentsOfFile:@"/Users/zxq/Desktop/userInfor"];
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
BOOL res2 = [fileManager createFileAtPath:testPath contents:data attributes:nil];
if (res2) {
NSLog(@"创建文件成功");
} else {
NSLog(@"创建文件失败");
}
测试写入内容
NSString *content = @"测试写入内容";
BOOL res3 = [content writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (res3) {
NSLog(@"文件写入成功");
} else {
NSLog(@"文件写入失败");
}
读取文件内容
NSString *content2 = [NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];
获取文件属性
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:testPath error:nil];
for (int i = 0; i < [[fileAttributes allKeys] count]; i ++) {
NSLog(@"key: %@, value:%@", [[fileAttributes allKeys] objectAtIndex:i], [fileAttributes objectForKey:[[fileAttributes allKeys] objectAtIndex:i]]);
}
删除文件
BOOL res4 = [fileManager removeItemAtPath:testPath error:nil];
if (res4) {
NSLog(@"删除成功");
} else {
NSLog(@"删除失败");
}