NSFileManager使用方法
NSString * filePath=@"/Users/nlp/Desktop/NSString_Test_01/NSString_Test_01/Info.plist";
单例
NSFileManager *fm=[NSFileManager defaultManager];
1.判断是否指定位置有内容(文件或文件夹)
BOOL haveaFile=[fm fileExistsAtPath:filePath];
2.判断指定位置是目录(文件夹)还是文件,例如桌面这种就是目录
BOOL isCatalogue;
BOOL haveFile=[fm fileExistsAtPath:filePathisDirectory:&isCatalogue];
*if(isCatalogue) {
NSLog(@"这是一个目录");
}else
{
NSLog(@"这是一个文件");
}
3.判断文件是否可读
BOOL canRead=[fm isReadableFileAtPath:filePath];
4.判断文件是否可写
BOOL canWrite=[fm isWritableFileAtPath:filePath];
5.判断文件是否可删除
BOOL canDelete=[fm isDeletableFileAtPath:filePath];
6.获取文件属性
NSDictionary * attDic=[fm attributesOfItemAtPath:filePatherror:nil];
NSLog(@"attDic=%@",attDic);
7.获取文件夹下所有子目录和子文件
NSArray* subArr=[fmsubpathsAtPath:filePath1];
NSLog(@"subArr=%@",subArr);
8.获取文件夹下所有子目录和子文件
NSArray* subArr1=[fm subpathsOfDirectoryAtPath:filePath1error:nil];
NSLog(@"subArr1=%@",subArr1);
9.获取文件夹下子目录(只包括子文件及目录,不包括二级目录)
NSArray* firstSubArr=[fm contentsOfDirectoryAtPath:filePath1error:nil];
NSLog(@"firstSubArr=%@",firstSubArr);
10.创建文件夹
YES:创建目录时,自动创建路径下缺少的目录
NO:不自动创建,如果中途缺少目录,则失败
attributes:
文件属性
BOOL createSuccess=[fm createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
11.创建文件
NSString * filePath2=@"/Users/nlp/Desktop/NSString_Test_01/NSString_Test_01/test.txt";
NSString * str=@"I love you";
NSData * strData=[str dataUsingEncoding:NSUTF8StringEncoding];
BOOL creatSuccess=[fm createFileAtPath:filePath2 contents:strData attributes:nil];
12.复制文件
NSString * copyPath=@"/Users/nlp/Desktop/NSString_Test_01/NSString_Test_02/test.txt";
NSError * error;
BOOL copySuccess=[fm copyItemAtPath:filePath2 toPath:copyPath error:&error];
13.移动文件
NSString * movePath=@"/Users/nlp/Desktop/NSString_Test_01/NSString_Test_02/test.txt";
BOOL moveSuccess=[fm moveItemAtPath:filePath2 toPath:movePath error:&error];
14.删除文件
BOOL deleteSuccess=[fm removeItemAtPath:filePath error:&error];