Foundation Framework 文件 NSFile​Manager

本文介绍如何使用NSFileManager在iOS应用中进行文件管理操作,包括检查文件存在性、列举目录内容、递归遍历目录、创建及删除目录等,并提供了常用的文件属性键。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文章

http://nshipster.cn/nsfilemanager/


确定文件是否存在

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"];
BOOL fileExists = [fileManager fileExistsAtPath:filePath];


列出文件里面的所有目录

NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSArray *contents = [fileManager contentsOfDirectoryAtURL:bundleURL
                               includingPropertiesForKeys:@[]
                                                  options:NSDirectoryEnumerationSkipsHiddenFiles
                                                    error:nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension == 'png'"];
for (NSURL *fileURL in [contents filteredArrayUsingPredicate:predicate]) {
    // 在目录中枚举 .png 文件
}


用递归的方式在目录中遍历文件

NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:bundleURL
                                      includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                         options:NSDirectoryEnumerationSkipsHiddenFiles
                                                    errorHandler:^BOOL(NSURL *url, NSError *error)
{
    if (error) {
        NSLog(@"[Error] %@ (%@)", error, url);
        return NO;
    }

    return YES;
}];

NSMutableArray *mutableFileURLs = [NSMutableArray array];
for (NSURL *fileURL in enumerator) {
    NSString *filename;
    [fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];

    NSNumber *isDirectory;
    [fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];

    // Skip directories with '_' prefix, for example
    if ([filename hasPrefix:@"_"] && [isDirectory boolValue]) {
        [enumerator skipDescendants];
        continue;
    }

    if (![isDirectory boolValue]) {
        [mutableFileURLs addObject:fileURL];
    }
}


创建一个目录

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *imagesPath = [documentsPath stringByAppendingPathComponent:@"images"];
if (![fileManager fileExistsAtPath:imagesPath]) {
    [fileManager createDirectoryAtPath:imagesPath withIntermediateDirectories:NO attributes:nil error:nil];
}]


删除一个目录

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"];
NSError *error = nil;

if (![fileManager removeItemAtPath:filePath error:&error]) {
    NSLog(@"[Error] %@ (%@)", error, filePath);
}


删除文件的创建日期

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"Document.pages"];

NSDate *creationDate = nil;
if ([fileManager fileExistsAtPath:filePath]) {
    NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath error:nil];
    creationDate = attributes[NSFileCreationDate];
}



通过NSFileManager的 -attributesOfItemAtPath:error: 和其它方法可以访问很多文件的属性

文件属性的键
  • NSFileAppendOnly: 文件是否只读
  • NSFileBusy: 文件是否繁忙
  • NSFileCreationDate: 文件创建日期
  • NSFileOwnerAccountName: 文件所有者的名字
  • NSFileGroupOwnerAccountName: 文件所有组的名字
  • NSFileDeviceIdentifier: 文件所在驱动器的标示符
  • NSFileExtensionHidden: 文件后缀是否隐藏
  • NSFileGroupOwnerAccountID: 文件所有组的group ID
  • NSFileHFSCreatorCode: 文件的HFS创建者的代码
  • NSFileHFSTypeCode: 文件的HFS类型代码
  • NSFileImmutable: 文件是否可以改变
  • NSFileModificationDate: 文件修改日期
  • NSFileOwnerAccountID: 文件所有者的ID
  • NSFilePosixPermissions: 文件的Posix权限
  • NSFileReferenceCount: 文件的链接数量
  • NSFileSize: 文件的字节
  • NSFileSystemFileNumber: 文件在文件系统的文件数量
  • NSFileType: 文件类型
  • NSDirectoryEnumerationSkipsSubdirectoryDescendants: 浅层的枚举,不会枚举子目录
  • NSDirectoryEnumerationSkipsPackageDescendants: 不会扫描pakages的内容
  • NSDirectoryEnumerationSkipsHiddenFile: 不会扫描隐藏文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值