———- android培训、java培训、期待与您交流! ———-
1、NSFileManager介绍
什么是NSFileManager ?
顾名思义, NSFileManager是用来管理文件系统的 ,
它可以用来进行常见的文件\文件夹操作(拷贝、剪切、创建等) ;
NSFileManager使用了单例模式singleton ,
使用defaultManager方法可以获得那个单例对象 ;
[NSFileManager defaultManager] ;
2、NSFileManager常用方法
1:创建文件操作对象
NSFileManager *fm = [NSFileManager defaultManager];
#define PATH @"/Users/boitx/Downloads/"
2:潜度遍历,深度遍历
NSArray *array = [fm contentsOfDirectoryAtPath:PATH error:&error];
//潜度遍历
array = [fm subpathsOfDirectorAtPath:PATH error:&error];
//深度遍历
3:创建文件,创建包含内容的文件
[fm createDirectoryAtPath:PARH withIntermediateDirectories:(BOOL) attributes:(NSDictionary)]; [fm createFileAtPath:PATH contents:(NSData *) attributes:(NSDictionary *)]
4:复制文件,删除文件
[fm removeItemAtPath:PATH error:&error]
[fm copyItemAtPath:Path toPath:newPath error:&error];
3、NSFileManager使用步骤
1、定义路径
NSString *path = @"/Users/liwei/Desktop/test/subcc/";
2、创建对象
NSFileManager *fileManager = [NSFileManager defaultManager];
3、创建目录
//createDirectoryAtPath 路径
//withIntermediateDirectories 是否自动创建路径中的所有文件夹
//attributes 文件夹属性
//error 错误信息
BOOL flag = [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
if (flag)
{
NSLog(@"目录创建成功!");
//写入文件
NSString *str =@"测试文件内容";
flag = [str writeToFile:[NSString stringWithFormat:@"%@/1.txt",path] atomically:YESencoding:NSUTF8StringEncoding error:nil];
if (flag)
{
NSLog(@"文件写入成功!");
}
}
拷贝,如果目标目录已经存在同名文件,则无法拷贝
- (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; //删除文件
创建文件:
ps:NSData是用来存储二进制字节数据的
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;
//创建文件,NSData是用来存储二进制字节数据的
把字符串转换为NSData
NSString *s1 =@"hello";
NSData *data = [s1 dataUsingEncoding:NSUTF8StringEncoding];
//把字符串转换为NSData
“`