[NSFileManager defaultmanager]是操作文件的单例,二次封装可方便使用:
YJFileTool.h
#import <Foundation/Foundation.h>
typedef enum {//文件存储位置
YJFileTypeDocument,
YJFileTypeCache,
YJFileTypeLibrary,
YJFileTypeTem
}YJFileType;
@interface YJFileTool : NSObject
/** 获取Document路径 */
+(NSString *)getDocumentPath;
/** 获取Cache路径 */
+(NSString *)getCachePath;
/** 获取Library路径 */
+(NSString *)getLibraryPath;
/** 获取Tem路径 */
+(NSString *)getTemPath;
/** 判断文件是否存在 */
+(BOOL)fileIsExists:(NSString *)path;
/**
* 创建目录下文件
* 一般来说,文件要么放在Document,要么放在Labrary下的Cache里面
* 这里也是只提供这两种存放路径
* @param fileName 文件名
* @param Type 路径类型
* @param context 数据内容
*
* @return 文件路径
*/
+(NSString *)createFileName:(NSString *)fileName type:(YJFileType)Type context:(NSData *)context;
/**
写入文件
@param filePath 文件路径
@param textData 内容
@return 是否成功
*/
+(BOOL)writeToFileName:(NSString *)filePath data:(NSData *)textData;
@end
YJFileTool.m
#import "YJFileTool.h"
@implementation YJFileTool
+(NSString *)getDocumentPath{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
+(NSString *)getCachePath{
return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
}
+(NSString *)getLibraryPath{
return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
}
+(NSString *)getTemPath{
return NSTemporaryDirectory();
}
+(NSString *)getRootPath:(YJFileType)type{
switch (type) {
case YJFileTypeDocument:
return [self getDocumentPath];
break;
case YJFileTypeCache:
return [self getCachePath];
break;
case YJFileTypeLibrary:
return [self getLibraryPath];
break;
case YJFileTypeTem:
return [self getTemPath];
break;
default:
break;
}
return nil;
}
+(BOOL)fileIsExists:(NSString *)path{
if (!path || path.length == 0) {
return NO;
}
return [[NSFileManager defaultManager] fileExistsAtPath:path];
}
+(NSString *)createFileName:(NSString *)fileName type:(YJFileType)Type context:(NSData *)context{
if (!fileName || fileName.length == 0) {
return nil;
}
NSString *rootPath = [[self getRootPath:Type] stringByAppendingString:fileName];
if ([self fileIsExists:rootPath]) {
if (![[NSFileManager defaultManager]removeItemAtPath:rootPath error:nil]) {
return nil;
}
}
if ([[NSFileManager defaultManager]createFileAtPath:rootPath contents:context attributes:nil]) {
return rootPath;
}
return nil;
}
//追加写文件
+(BOOL)writeToFileName:(NSString *)filePath data:(NSData *)textData{
if (![self fileIsExists:filePath]) {
return NO;
}
if (textData.bytes>0) {
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:textData];
[fileHandle synchronizeFile];
[fileHandle closeFile];
return YES;
}else{
return NO;
}
}
@end
更多操作,请参考:https://blog.youkuaiyun.com/feng2qing/article/details/54974200