• < Objective-C >文件操作-NSFileManager


    NSFileManager主要负责创建与删除等操作

    NSFileManager类主要方法

    +(NSFileManager *)defaultManager;获得文件管理器对象
    -(BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;创建文件
    -(BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error;创建目录
    -(BOOL)fileExistsAtPath:(NSString *)path;判断一个文件或目录是否存在
    -(BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory;判断文件是否存在且判断path是文件还是目录
    -(BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;文件或目录复制
    -(BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;文件或目录移动
    -(BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;文件或目录删除
     
     
    创建文件代码
    //创建文件
    NSFileManager *fm = [NSFileManager defaultManager];  //创建文件管理器
            
    NSString *path = @"/Users/ni/Desktop/input.txt";
    NSString *str = @"Hello World!";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];  //将str转化为NSData类型
            
    BOOL flag = [fm createFileAtPath:path contents:data attributes:nil];
    if(flag) {
        NSLog(@"create success!");
    } else {
        NSLog(@"create fail!");
    }

    读取文件代码

    //读取文件
    NSString *fileContent = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",fileContent);

    NSData:用来设置缓冲区,将文件内容读入缓冲区,或将缓冲区的内容写到一个文件

    目录(文件夹)操作:遍历方法
    -(NSDirectoryEnumerator *)enumeratorAtPath:(NSString *)path;深度遍历(遍历所有子文件夹),返回目录枚举器(NSDirectoryEnumerator)
    -(NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;浅度遍历,返回目录中的所有文件&文件夹的名字

    NSString *dirPath = @"/Users/ni/Desktop/workspace";
    NSFileManager *fm = [NSFileManager defaultManager];
    
    //深度遍历
    NSDirectoryEnumerator *dirs = [fm enumeratorAtPath:dirPath];        
    NSString *path = [dirs nextObject];
    while (path != nil) {
        NSLog(@"%@",path);
        path = [dirs nextObject];
    }
         
    //浅度遍历   
    NSArray *arr = [fm contentsOfDirectoryAtPath:dirPath error:nil];
    NSLog(@"%@", arr);

    NSDirectoryEnumerator类有两个方法
    -(id)nextObject;
    -(NSArray *)allObjects;

  • 相关阅读:
    optorsim自带例子调试总结
    搭建Hadoop2.0(三)自带实例运行
    被遮挡的绝对定位
    Javascript获取地址参数
    js屏蔽浏览器(IE和FireFox)的刷新和右键等功能
    Tencent://Message/协议的实现原理
    Form(思归):动态控件的状态问题
    [正则表达式]C# 给数字字符串加上千位逗号
    js滚动条
    模拟滚动条效果
  • 原文地址:https://www.cnblogs.com/aY-Wonder/p/4562723.html
Copyright © 2020-2023  润新知