1递归,查找文件的方法怎么写,(查找当前路径下的所有文件的数量)步骤:
解决方案:1.创建一个查找文件的方法:带参数 , 在方法中创建一个FlieManager对象 NSFileManager *fm = [NSFileManagerdefaultManager];
2.文件夹下面的内容是数组,所以在上行代码下面要用数组进行实现 NSArray *fileNames = [fm contentsOfDirectoryAtPath:path error:nil];获取数组路径下的所有文件内容:
3.遍历数组,在其中进行判断
for (NSString *fileName in fileNames) {
//开始
if ([fileName hasSuffix:@"jpg"]||[fileNamehasSuffix:@"png"]) {
Nslog(@"%@",filename); 找到桌面的所有图片并输出 如果要删除的话:【FMREMOVEATPATH FILEPATH ERROR:NIL】;加上这个
下一个需求,将找到的所有图片全都删掉的话:
需要找到桌面图片的完整路径 :
NSString *filePath= [path stringByAppendingPathComponent:fileName];需要将当前文件夹的路径和图片名拼接到一起。
//判断是否为文件夹:
BOOL isDir = NO;
if ([fm fileExistsAtPath:filePathisDirectory:&isDir]&&isDir){
[selffindFileInDirecotryPath:filePath];//如果是文件夹,继续查看它下面的内容;
}
NSString *toPath = [@"/Users/bmuyu/Desktop/imgs"stringByAppendingPathComponent:fileName]; //将桌面的所有图片移动到这个路径下。
[selffindFileInDirecotryPath:@"/Users/"];
}
完整代码的意思是 查找Users路径下所有PNG和JPG格式的图片移动到/Users/bmuyu/Desktop/imgs这个路径下 然后做一个计数,需要声明int变量
-(void)findFileInDirecotryPath:(NSString *)path{
NSFileManager *fm = [NSFileManagerdefaultManager];
NSArray *fileNames = [fm contentsOfDirectoryAtPath:path error:nil];
for (NSString *fileName in fileNames) {
NSString *filePath =[path stringByAppendingPathComponent:fileName];
//开始
if ([fileName hasSuffix:@"jpg"]||[fileNamehasSuffix:@"png"]) {
self.count++;//图片计数~
NSLog(@"%d",self.count);
//准备新的路径仍然是原来的文件名称
NSString *toPath = [@"/Users/bmuyu/Desktop/imgs"stringByAppendingPathComponent:fileName];
[fm moveItemAtPath:filePathtoPath:toPatherror:nil];
}
//判断是否是文件夹
BOOL isDir = NO;
if ([fm fileExistsAtPath:filePathisDirectory:&isDir]&&isDir){
[selffindFileInDirecotryPath:filePath];
}