ios 沙盒文件创建,读取,写入,删除封装
注:沙盒写入log的话 xcode只能在debug模式下才能整体导出读取内容,线上release版本是没有权限导出读取的,release版本日志可以使用idevicesyslog mac配合读取
1.创建
NSString *pathDocuments = [self documentsDir]; //获取沙盒documents目录 //要创建的文件夹,与文件 NSString *logInfo = [NSString stringWithFormat:@"%@/taskLog/%@", pathDocuments,[mainScheme getNowDate]]; NSString *logInfoFile = [NSString stringWithFormat:@"%@/taskLog/%@/%@.txt", pathDocuments,[mainScheme getNowDate],deviceId]; NSLog(@"createPath = %@",logInfoFile); // 判断文件夹是否存在,如果不存在,则创建 if (![[NSFileManager defaultManager] fileExistsAtPath:logInfo]) { //创建文件夹 [[NSFileManager defaultManager] createDirectoryAtPath:logInfo withIntermediateDirectories:YES attributes:nil error:nil]; //创建文件 [[NSFileManager defaultManager] createFileAtPath:logInfoFile contents:nil attributes:nil]; NSLog(@"FileDir is success."); } else { NSLog(@"FileDir is exists."); } + (NSString *)documentsDir { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; }
2.写入追加
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:logInfoFile]; //获取对文件写入的权限 [fileHandle seekToEndOfFile]; // 可以操作光标到文件内容的末尾。这样就可以在内容后面进行再一次添加啦 NSString *logInfoData = [NSString stringWithFormat:@"%@ serverKey -> %@ , original task : %@ \n", [dataOrig objectForKey:@"deviceId"],[dataOrig objectForKey:@"serverKey"],[dataOrig objectForKey:@"data"]]; NSData * writeDatas = [logInfoData dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:writeDatas]; // 在文件末尾写入数据 [fileHandle closeFile];
3.读取
+(NSString *)readFileData:(NSString *)filePath{ NSFileHandle *fileHandleread = [NSFileHandle fileHandleForReadingAtPath:filePath]; //获取对文件写入的权限 NSData *info = (NSData *)[fileHandleread readDataToEndOfFile]; NSString *result = [[NSString alloc] initWithData:info encoding:NSUTF8StringEncoding]; NSLog(@"FileDir info. %@",result); [fileHandleread closeFile]; return result; }
4.删除
+ (BOOL)removeItemAtPath:(NSString *)path { return [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; }
5.文件夹遍历
+ (NSArray *)listFilesInDirectoryAtPath:(NSString *)path deep:(BOOL)deep { NSArray *listArr; NSError *error; NSFileManager *manager = [NSFileManager defaultManager]; if (deep) { // 深遍历 NSArray *deepArr = [manager subpathsOfDirectoryAtPath:path error:&error]; if (!error) { listArr = deepArr; }else { listArr = nil; } }else { // 浅遍历 NSArray *shallowArr = [manager contentsOfDirectoryAtPath:path error:&error]; if (!error) { listArr = shallowArr; }else { listArr = nil; } } return listArr; }
本文章仅供学习参考,如有版权侵犯,请联系作者修改,转载请注明出处!