NSFileManager – Discovering Directory Contents

Step 1

遍历根目录下所有的文件和文件夹,如下:

1int main (int argc, const char * argv[]) {
2    @autoreleasepool {
3        NSFileManager* mgr = [NSFileManager defaultManager];
4        NSArray* contents = [mgr contentsOfDirectoryAtPath:@"/" error:nil];
5        for (id each in contents) {
6            NSLog(@"%@", each);
7        }
8    }
9}
  • NSFileManager负责操作文件系统,隔离应用层和底层文件系统,NSFileManager采用singleton模式
  • contentsOfDirectoryAtPath根据传入的路径返回此目录下的content,content包括了文件和文件夹,以及以.开头的隐藏文件
  • 在iOS 5.0和Mac OS X v10.7在后NSFileManager支持Cloud文件操作

考虑到可能由于路径错误或是权限因素导致的错误,可以通过传入error的pointer,通过error查看错误原因

1NSError* error;
2NSArray* contents = [mgr contentsOfDirectoryAtPath:@"/WRONG" error:&error];
3if (error != nil) {
4      NSLog(@"%@", [error localizedDescription]);
5      NSLog(@"%@", [error userinfo]);
6}

当我们需要查找Home路径(/Users/nonocast/)时一定会想到传入’~',不过却返回error,说The folder “~” doesn’t exist.
所以我们要使用NSHomeDirectory()来返回,如下:

1[mgr contentsOfDirectoryAtPathNSHomeDirectory() error:&error];

那么如果需要做到Path.Combine(c#)则需要借助NSString,下面代码对应到~/Library目录下:

1path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
2NSArray* contents = [mgr contentsOfDirectoryAtPath: path error:&error];

也可以这样:

1path = [NSString pathWithComponents:[[NSArrayalloc]initWithObjects:@"/",@"Users/nonocast"@"Library",nil]];

现在我们可以通过构建路径来查询路径下所有的内容了。

Step 2

我们在上面的基础上进行区分文件夹和文件,可惜contentsOfDirectoryAtPath返回的仅仅是文件名,我们不得不改用一个相对复杂些的方法contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:,通过URL来返回URL,Apple建议开发人员采用URL的方式来表达路径

The preferred way to specify the location of a file or directory is to use the NSURL class. Although the NSString class has many methods related to path creation, URLs offer a more robust way to locate files and directories. For applications that also work with network resources, URLs also mean that you can use one type of object to manage items located on a local file system or on a network server.

代码如下:

01NSFileManager* mgr = [NSFileManager defaultManager];
02 
03NSString* path = [NSHomeDirectory()stringByAppendingPathComponent:@"Downloads"];
04NSURL* url = [[NSURL alloc]initWithString:path];
05NSArray* contents = [mgr contentsOfDirectoryAtURL:urlincludingPropertiesForKeys:[NSArray array]options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
06 
07for (NSURL* each in contents) {
08    NSString* filename;
09    NSNumber* isDirectory;
10    NSNumber* filesize;
11 
12    [each getResourceValue:&filename forKey:NSURLNameKey error:nil];
13    [each getResourceValue:&isDirectory forKey:NSURLIsDirectoryKeyerror:nil];
14    [each getResourceValue:&filesize forKey:NSURLFileSizeKey error:nil];
15 
16    if([isDirectory boolValue]){
17        NSLog(@"[D] %@", filename);
18    else {
19        NSLog(@"[F] %@ (%@ bytes)", filename, filesize);
20    }
21}

我们通过getResourceValue获取了文件名字、判断出文件还是目录以及文件大小,参看以下定义:

Common File System Resource Keys

  • NSURLNameKey
  • NSURLLocalizedNameKey
  • NSURLIsRegularFileKey
  • NSURLIsDirectoryKey
  • NSURLIsSymbolicLinkKey
  • NSURLIsVolumeKey
  • NSURLIsPackageKey
  • NSURLIsSystemImmutableKey
  • NSURLIsUserImmutableKey
  • NSURLIsHiddenKey
  • NSURLHasHiddenExtensionKey
  • NSURLCreationDateKey
  • NSURLContentAccessDateKey
  • NSURLContentModificationDateKey
  • NSURLAttributeModificationDateKey
  • NSURLLinkCountKey
  • NSURLParentDirectoryURLKey
  • NSURLVolumeURLKey
  • NSURLTypeIdentifierKey
  • NSURLLocalizedTypeDescriptionKey
  • NSURLLabelNumberKey
  • NSURLLabelColorKey
  • NSURLLocalizedLabelKey
  • NSURLEffectiveIconKey
  • NSURLCustomIconKey
  • NSURLFileResourceIdentifierKey
  • NSURLVolumeIdentifierKey
  • NSURLPreferredIOBlockSizeKey
  • NSURLIsReadableKey
  • NSURLIsWritableKey
  • NSURLIsExecutableKey
  • NSURLIsMountTriggerKey
  • NSURLFileSecurityKey
  • NSURLFileResourceTypeKey

File Property Keys

  • NSURLFileSizeKey
  • NSURLFileAllocatedSizeKey
  • NSURLIsAliasFileKey
  • NSURLTotalFileAllocatedSizeKey
  • NSURLTotalFileSizeKey

t通过2个Step已经可以完成定位目录,遍历目录下所有文件这些基础的不能再基础的功能,好辛苦啊…这个你们不懂的…后面就学习如何操作文件。对了,2个Step都是在mac上做的测试,比开simulate方便,Step3就接着写iphone/ipad下的文件目录操作,听说有sandbox限制,同时看下JB是否有所区别。

原文地址:https://www.cnblogs.com/jacktu/p/2245399.html