美文网首页
iOS中的NSFileManager--文件管理二

iOS中的NSFileManager--文件管理二

作者: 金鱼________ | 来源:发表于2017-03-16 16:54 被阅读0次

    NSFileManager:用于执行一般的文件系统操作,主要功能包括:从一个文件中读取数据,向一个文件中写入数据,删除文件,复制文件,移动文件,比较两个文件的内容,测试文件的存在性,读取/更改文件的属性等

    访问NSFileManager,使用共享的管理器对象

    NSFileManager *fileManager = [NSFileManager defaultManager];

    允许对NSFileManager设置代理,用于当文件管理器完成一项操作,如复制或移动文件操作时,接受相应的信息,设置代理时,需要创建自己的NSFileManager实例,而不是使用共享实例

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    fileManager.delegate = self;

    一、判断一个给定路径是否为文件夹

    - (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(nullable BOOL *)isDirectory;

    BOOL createPathOK = YES;

    [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&createPathOK];

    二、文件夹/文件的创建

    #pragma mark - 文件的创建

    -(void)createFile{

    //创建文件管理器

    NSFileManager *fileManager = [NSFileManager defaultManager];

    //指向文件目录(沙盒中的Documents文件夹)

    NSString *documentDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

    NSLog(@"%@",documentDirectory);

    //在Documents文件夹下创建一个名为“myFolder”的文件夹

    [fileManager createDirectoryAtPath:[documentDirectory stringByAppendingPathComponent:@"myFolder"] withIntermediateDirectories:YES attributes:nil error:nil];

    //在Documents创建一个文件

    NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"file.txt"];

    NSString *str = @"用来测试";

    //文件中添加内容,生成文件

    //对于错误信息

    NSError *error;

    [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

    }

    二、获取文件夹下的文件目录

    NSArray *content = [fileManager contentsOfDirectoryAtPath:documentDirectory error:&error];

    三、移除路径所到的文件

    [fileManager removeItemAtPath:filePath error:&error];

    四、路径下是否存在文件

    BOOL isExist = [fileManager fileExistsAtPath:filePath];

    五、总结

    //常见的NSFileManager处理文件的方法如下:

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    NSData *myData = [fileManager contentsAtPath:path];//从一个文件中读取数据

    [fileManager createFileAtPath:path contents:myData attributes:dic];//向一个文件中写入数据,属性字典允许自己制定

    [fileManager removeItemAtPath:path error:error];//删除路径所指向的文件或文件夹

    [fileManager copyItemAtPath:path1 toPath:path2 error:error];//复制文件内容粘贴到别处

    [fileManager fileExistsAtPath:path];//路径下是否存在文件或文件夹

    [fileManager enumeratorAtPath:path];//获取目录的内容列表,一次可以枚举指定目录中的每个文件

    相关文章

      网友评论

          本文标题:iOS中的NSFileManager--文件管理二

          本文链接:https://www.haomeiwen.com/subject/mocjnttx.html