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

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

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

1 //
2  // Main.m
3 // FileWalker
4 // 查找主目录中某类型(.jpg)文件并输出找到的文件列表。
5 //
6 // Created by Elf Sundae on 10/23/10.
7 // Copyright 2010 Elf.Sundae(at)Gmail.com. All rights reserved.
8 //
9 #import <Foundation/Foundation.h>
10
11 int main (int argc, const char * argv[]) {
12 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
13
14 // 创建NSFileManager
15 NSFileManager *fileManager = [NSFileManager defaultManager];
16 // 指定目录为主目录(~):(/Users/ElfSundae)
17 // stringByExpandingTildeInPath方法将路径展开为fullpath
18 NSString *home = [@"~" stringByExpandingTildeInPath];
19 // 将路径字符串传给文件管理器
20 //An NSDirectoryEnumerator object enumerates
21 //the contents of a directory, returning the
22 //pathnames of all files and directories contained
23 //within that directory. These pathnames are relative
24 //to the directory.
25 //You obtain a directory enumerator using
26 //NSFileManager’s enumeratorAtPath: method.
27
28 //* NSDirectoryEnumerator *direnum=[fileManager enumeratorAtPath:home];
29 //
30 // // 可以在迭代中直接输出路径。
31 // // 这里先存储到数组中再输出
32 // NSMutableArray *files = [NSMutableArray arrayWithCapacity:42];
33 //
34 // NSString *fileName;
35 // while (fileName = [direnum nextObject]) {
36 // if ([[fileName pathExtension] isEqualTo:@"jpg"]) {
37 // [files addObject:fileName];
38 // }
39 //* }
40
41 // 或者使用快速枚举迭代
42 NSMutableArray *files = [NSMutableArray arrayWithCapacity:42];
43 for (NSString *fileName in [fileManager enumeratorAtPath:home])
44 {
45 if ([[fileName pathExtension] isEqualTo:@"jpg"]) {
46 [files addObject:fileName];
47 }
48 }
49
50
51 //* NSEnumerator *jpgFiles = [files objectEnumerator];
52 // while (fileName = [jpgFiles nextObject]) {
53 // NSLog(@"%@",fileName);
54 //* }
55
56 // 或者用快速枚举输出
57 for ( NSString *jpg in files)
58 {
59 NSLog(@"%@",jpg);
60 }
61
62
63
64 [pool drain];
65 return 0;
66 }
67

 

posted @ 2010-10-25 03:30  Elf Sundae  阅读(1800)  评论(3编辑  收藏  举报