您的位置:首页 > 移动开发 > Objective-C

Objective-C边学边记-11:Foundation Kit快速教程之 综合示例(查找某类型的文件)

2010-10-25 03:30 573 查看
7.综合示例:查找文件
程序功能:查找主目录中某类型(.jpg)文件并输出找到的文件列表。
NSFileManager提供对文件系统的操作,如创建目录、删除文件、移动文件或者获取文件信息。在这个例子里,将使用NSFileManager创建NSdirectoryEnumerator来遍历文件的层次结构。

使用了两种方法遍历:俺索引枚举 和 快速枚举 (见注释说明):

//
//  Main.m
//  FileWalker
//  查找主目录中某类型(.jpg)文件并输出找到的文件列表。
//
//  Created by Elf Sundae on 10/23/10.
//  Copyright 2010 Elf.Sundae(at)Gmail.com. All rights reserved.
//
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

// 创建NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
// 指定目录为主目录(~):(/Users/ElfSundae)
// stringByExpandingTildeInPath方法将路径展开为fullpath
NSString *home = [@"~" stringByExpandingTildeInPath];
// 将路径字符串传给文件管理器
//An NSDirectoryEnumerator object enumerates
//the contents of a directory, returning the
//pathnames of all files and directories contained
//within that directory. These pathnames are relative
//to the directory.
//You obtain a directory enumerator using
//NSFileManager’s enumeratorAtPath: method.

//*    NSDirectoryEnumerator *direnum=[fileManager enumeratorAtPath:home];
//
//    // 可以在迭代中直接输出路径。
//    // 这里先存储到数组中再输出
//    NSMutableArray *files = [NSMutableArray arrayWithCapacity:42];
//
//    NSString *fileName;
//    while (fileName = [direnum nextObject]) {
//        if ([[fileName pathExtension] isEqualTo:@"jpg"]) {
//            [files addObject:fileName];
//        }
//*    }

// 或者使用快速枚举迭代
NSMutableArray *files = [NSMutableArray arrayWithCapacity:42];
for (NSString *fileName in [fileManager enumeratorAtPath:home])
{
if ([[fileName pathExtension] isEqualTo:@"jpg"]) {
[files addObject:fileName];
}
}

//*    NSEnumerator *jpgFiles = [files objectEnumerator];
//    while (fileName = [jpgFiles nextObject]) {
//        NSLog(@"%@",fileName);
//*    }

// 或者用快速枚举输出
for ( NSString *jpg in files)
{
NSLog(@"%@",jpg);
}

[pool drain];
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: