文件操作NSManager
//1对文件本身的操作
NSManager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | //创建一个单例的file manager 的对象 NSFileManager *fm=[ NSFileManager defaultManager]; //浅度遍历 //查看指定目录下的文件 把获得的文件和文件夹的名字放到数组里 返回值是数组的地址 NSEroor *error= nil ; //指针的地址 NSArray *array= [fm contentsOfDirectoryAtPath:(文件路径)error:&error]; if (error){ NSLog (@ "@" ,error); exit(-1); } NSLog (@ "%@" ,array); //深度遍历 array=[fm subpathsOfDirectoryAtPath:(文件路径)error:&error]; if (error){ NSLog (@ "@" ,error); exit(-1); } NSLog (@ "%@" ,array); //创建目录 [fm createDirectoryAtPath:[ NSString stringWithFormat:@ "%@/middle/dir" ,路径名] withIntermediateDirectories:(是否有中间路径,如果 NO 则会报错) attributes: nil error:&error ]; if (error){ NSLog (@ "@" ,error); exit(-1); } //创建文件 [fm createFileAtPath:[ NSString stringWithFormat:@ "%@/middle/dir/file" ,路径名] contents:( NSData *)文件的内容(可以不先写内容 让它为 nil ) attributes:文件属性(填 nil 表示使用默认的属性) ]; //文件的删除(可以删除文件、文件夹、目录) [fm removeItemAtPath:[ NSString stringWithFormat:@ "%@/middle" ,路径名] error:&error]; if (error){ NSLog (@ "@" ,error); exit(-1); } //拷贝 和删除一样 不分文件和目录 [fm copyItemAtPath:[ NSString stringWithFormat:@ "%@/dir" ,路径名](原文件的路径) toPath:[@ "%@/dir1" ,路径名](生成的文件的路径) error:&error ]; if (error){ NSLog (@ "@" ,error); exit(-1); } //移动文件(剪切) [fm moveItemAtPath:[ NSString stringWithFormat:@ "%@/dir" ,路径名](原文件的路径) toPath:[@ "%@/dir2" ,路径名](生成的文件的路径) error:&error ]; if (error){ NSLog (@ "@" ,error); exit(-1); } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步