zoukankan      html  css  js  c++  java
  • < 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;

  • 相关阅读:
    转来的:Diablo中的七大套装背景
    我的单元测试认识之路(下)
    《You can do it!》的chapter 2笔记
    一个枚举的简单应用
    仿百度的搜索下拉提示
    简单的 菜单当前选中 解决思路
    单元测试框架NUnit 之 Attributes特性(一)
    单元测试框架NUnit 之 constraints 约束
    分享个自己的ajax封装
    开源单元测试工具 Nunit
  • 原文地址:https://www.cnblogs.com/aY-Wonder/p/4562723.html
Copyright © 2011-2022 走看看