读写文件,具体内容看注释
+(void)writeFileName:(NSString *)fileName Type:(NSString *)type Data:(NSData *)data{
//获取沙盒路径 document
NSString *filePathStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//document下想要写入的文件
NSString *fullPathStr = [filePathStr stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",fileName,type]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:fullPathStr]) {
//创建目录
[fileManager createDirectoryAtPath:filePathStr withIntermediateDirectories:YES attributes:nil error:nil];
}
if ([fileManager fileExistsAtPath:fullPathStr]) {//在已存在的文件后面追加内容
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:fullPathStr];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
}
else {//不存在文件时,创建并写入内容
[data writeToFile:fullPathStr atomically:YES];
}
}
+(NSData *)readFileName:(NSString *)name Type:(NSString *)type{
NSString *filePathStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fullPathStr = [filePathStr stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",name,type]];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:fullPathStr];
return [fileHandle readDataToEndOfFile];
}