——黑马程序员——OC中Foundation下NSFileManager的使用

来源:互联网 发布:淘宝店铺中心在哪里找 编辑:程序博客网 时间:2024/05/19 21:03

-----------android培训java培训、java学习型技术博客、期待与您交流!-----------

OC中Foundation下NSFileManager的使用

一、NSFileManager介绍

OC 中用来管理文件系统,是文件管理类;类似C语言中的文件操作、

NSFileManager 使用了单例模式singletion

单例对象:在文件运行期间只有一个对象存在

使用defaultManager方法可以获得那个单例对象

[NSFileManager defaultManager];

二、NSFileManagner基本用法中常见判断

// 1、文件是否存在

NSString *filePath = @"/User/administator/Desktop/.....";

//(1)创建文件管理对象

//(2)调用defaultManager创建一个文件管理的单例对象

单例对象:在文件运行期间只有一个对象存在

NSFileManager *fm = [NSFileManager  defaultManager ];

//(3)判断文件是否存在

BOOL isYES =  [ fm fileExistsAtPath: filePath ];  //  返回值是BOOL类型的,YES时表示存在,

//2、文件是否是一个目录

if (isYES){

BOOL  isDir;

  [ fm  fileExistsAtPath isDirectory:  &isDir];

if(isDir){

NSLog(@"这是一个目录");

}else{

NSLog(@"这是不一个目录");

}

}

// 3、判断文件是否可读

BOOL isred = [ fm isReadableFileAtPath: filePath ];

// 4、判断文件是否可写

BOOL iswrit = [fm  isWritableFileAtPath: filePath];

// 5、判断文件是否可删除

BOOL  isdele = [fm isDeleatableFileAtPath:filePath];

三、NSFileManager 的创建目录及深入用法

// 1、获取文件的属性

[ fm  attributesOfItemAtPath: filePath  error :nil];  返回值是一个字典类型,

// 2、获取指定目录下的文件及子目录

[fm subpathAtPath: filePath ];

此方法使用的递归的方式,获取当前目录及子目录下的所有文件及文件夹,递归的方式效率低,耗内存

[fm subpathOfDirectoryAtPath:filePath ];

此方法不是使用的递归的方式,获取当前目录及子目录下的所有文件及文件夹,推荐使用此方法,

// 3、获取指定目录的下的子目录,而不获取后代元素

[fm contentsOfDirectoryAtPath: filePath  error nil];

4、NSFileManager 创建目录

创建文件管理对象

NSFileManager *fm  = [NSFileManager  defaultManager ];

[fm createDirectorAtPath:(@"路径") withIntermediateDirectories:(YES或者NO,创建路径的时候如果没有路径就会直接创建一个路径)attributes:(文件属性的字典) error:(错误对象) ];

[fm createDirectorAtPath:(@"路径") withIntermediateDirectories:YES attributes: nil  error:nil];  

返回值是BOOL类型的

5、NSFileManager创建文件

 [ fm   createFileAtPath: @"路径"  contents:  (NSDate 类型的数据) attributes:文件属性的字典];

// 创建NSData 或者将NSString类型的转换为NSData类型 ,NSData是处理二进制数据的一个类

NSString *str  = @"黑马训练营黑马程序员";

NSData *data = [ str  dataUsingEncoding:  NSUTF8StringEncoding  ];  //  将str 转换为NSData 类型的数据

 [ fm   createFileAtPath: @"路径"  contents:    attributes:data  attributes: nil ];

在某个目录下创建文件并把 str 写入到文件中去

6、NSFileManager如何  copy文件

 [ fm   copyItemAtPath: (NSString  *)路径  toPath: (NSString *)路径 error:(NSString *)];

7、NSFileManager移动文件

[fm  moveIterAtPath: @“路径”   toPath :@“另一路径” error (NSString  *)];

8、NSFileManager删除文件

[fm  removeIterAtPath: @“路径”  error (NSString  *)];

0 0
原创粉丝点击