免费开源的iOS开发学习平台

OC文件管理:1-NSFileManager类:文件操作

基于NSFileManager类,允许用户对文件进行基本操作,这些操作包括:创建新的文件、读取文件、对文件进行复制、移动以及删除等等,同时还可以对文件的一些常规属性进行读取以及修改。

基本概念

在学习NSFileManager类的相关属性和方法之前,需要提前了解并掌握如下几个与文件相关的基本概念。

  • 路径Path:在使用NSFileManager类对文件进行操作时,经常需要使用到路径的概念,路径我们可以理解为文件的物理存储路径+文件名称的组合,每个路径名都是一个NSString类型的对象。
  • 属性Attr:文件的属性是一个NSDictionary类型的对象,文件属性定义在Foundation/NSFileManager.h文件中,大概有20几个。
  • 错误err:一个指向NSError对象的指针,能提供有关文件操作更多的错误信息,如果err被置为nil,那么就会采取默认的错误处理行为。

基本操作

在使用NSFileManager类时,需要实例化一个NSFileManager类的对象,然后对指定路径Path上的文件进行一些操作。下方的代码,演示了如何获取目录,如何获取路径(这里要注意区分路径和目录的区别),如何实例化NSFileManager类,以及如何判断一个文件是否存在。

  • 我们首先在电脑的桌面上创建一个myfile.txt文件,可以打开终端,执行如下命令:
cd $HOME/Desktop/
touch myfile.txt
  • 文件准备完成后,在main()函数中添加下方的代码。需要注意的是:文件的路径可以通过两种方式来获取,第一种是直接给出绝对路径,另外一种是通过NSSearchPathForDirectoriesInDomains()函数来获取。
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //目录路径Path:绝对路径
        NSString *directoryPath = @"/Users/shixin/Desktop";
        //通过NSSearchPathForDirectoriesInDomains()函数获取路径
        NSArray * paths = NSSearchPathForDirectoriesInDomains (NSDesktopDirectory, NSUserDomainMask, YES);
        NSString * desktopPath = [paths objectAtIndex:0];
        
        //文件路径
        //注意:拼接文件名称需要使用stringByAppendingPathComponent:方法
        NSString *filePath1 = [directoryPath stringByAppendingPathComponent:@"myfile.txt"];
        NSString *filePath2 = [desktopPath stringByAppendingPathComponent:@"myfile.txt"];

        //实例化NSFileManager对象
        NSFileManager *fm = [NSFileManager defaultManager];

        //判断路径文件是否存在
        if ([fm fileExistsAtPath:filePath1]) {
            NSLog(@"myfile.txt exist in filePath!");
        }
        
        if ([fm fileExistsAtPath:filePath2]) {
            NSLog(@"myfile.txt exist in desktopPath!");
        }
    }
    return 0;
}

运行结果:

文件的复制、移动、重命名与删除

在开发过程中,涉及到对文件进行复制、移动、重命名以及删除等操作,在NSFileManager类中也提供了对应的方法。

  • 复制文件
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
  • 移动文件:该除了移动文件外,还可以用于文件改名
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
  • 删除文件
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;

示例代码:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //目录路径Path:绝对路径
        NSString *directoryPath = @"/Users/shixin/Desktop";
        //文件路径
        NSString *filePath = [directoryPath stringByAppendingPathComponent:@"myfile.txt"];
        //实例化NSFileManager对象
        NSFileManager *fm = [NSFileManager defaultManager];
        
        //复制文件
        NSString *copyFilePath = [directoryPath stringByAppendingPathComponent:@"myfilecopy.txt"];
        if ([fm fileExistsAtPath:copyFilePath] == NO) { //文件不存在,则创建
            if ([fm copyItemAtPath:filePath toPath:copyFilePath error:nil] ) {
                NSLog(@"file copy success!");
            }
        }

        //移动文件:除了移动文件外,还可以用于文件改名
        NSString *moveFilePath = [directoryPath stringByAppendingPathComponent:@"myfileNEWcopy.txt"];
        if ([fm fileExistsAtPath:filePath]) { //文件存在,则移动文件到moveFilePath
            if ([fm moveItemAtPath:filePath toPath:moveFilePath error:nil]) {
                NSLog(@"file move success");
            }
        }
        
        //删除文件
        if ([fm removeItemAtPath:moveFilePath error:nil]) {
            NSLog(@"file remove success");
        }
    }
    return 0;
}

运行结果。可以看到myfile.txt文件被成功的拷贝、移动(重命名)以及删除。

获取与修改文件属性

每个文件都有一些其自身属性,例如:文件大小、文件类型、文件所有者等等,我们可以使用NSFileManager来读取以及修改指定路径上文件的属性。

  • 获取文件属性: 可以使用attributesOfItemAtPath:方法来获取文件的属性,返回值是一个字典,其中存储了该目标文件的属性。下面的代码中,通过attributesOfItemAtPath:方法来获取了一个文件的所有属性,并且打印了文件的NSFileOwnerAccountName以及NSFileCreationDate两个属性。
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //目录路径Path:绝对路径
        NSString *directoryPath = @"/Users/shixin/Desktop";
        //文件路径
        NSString *filePath = [directoryPath stringByAppendingPathComponent:@"myfile.txt"];
        //实例化NSFileManager对象
        NSFileManager *fm = [NSFileManager defaultManager];
        
        NSDictionary *fileAttr = [fm attributesOfItemAtPath:filePath error:nil];
        NSLog(@"file owner name: <%@>, file create date:<%@>",fileAttr[NSFileOwnerAccountName],fileAttr[NSFileCreationDate]);
    }
    return 0;
}

运行结果:

文件的属性列表可以在Foundation/NSFileManager.h文件中查询,常用的一些属性如下所示。

NSFileAttributeKey const NSFileType; //文件类型
NSFileAttributeKey const NSFileSize; //文件大小
NSFileAttributeKey const NSFileCreationDate; //文件创建日期
NSFileAttributeKey const NSFileModificationDate; //文件修改日期
NSFileAttributeKey const NSFileOwnerAccountName; //文件所有人
  • 更改文件属性: 使用setAttributes:ofItemAtPath:error:方法来设置文件属性,在调用该方法之前,需要把希望改变的属性,封装在一个字典中,如下所示,下方的代码更改了文件的创建时间NSFileCreationDate
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        //目录路径Path:绝对路径
        NSString *directoryPath = @"/Users/shixin/Desktop";
        //文件路径
        NSString *filePath = [directoryPath stringByAppendingPathComponent:@"myfile.txt"];
        //实例化NSFileManager对象
        NSFileManager *fm = [NSFileManager defaultManager];
        //更改文件属性
        NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantFuture],NSFileCreationDate, nil];
        [fm setAttributes:attrDict ofItemAtPath:filePath error:nil];
        NSDictionary *fileAttr = [fm attributesOfItemAtPath:filePath error:nil];
        NSLog(@"file create date:<%@>",fileAttr[NSFileCreationDate]);
    }
    return 0;
}

运行结果:

示例代码

https://github.com/99ios/4.7.1