oc NSFileManager 文件夹创建、文件移动、文件复制、文件重命名

来源:互联网 发布:mac 玩天涯明月刀 编辑:程序博客网 时间:2024/05/16 08:09

    // 初始化管理类

        NSFileManager * manager = [NSFileManagerdefaultManager];

        

        // 路径

        NSString * DirectoryPath = [NSHomeDirectory()stringByAppendingPathComponent:@"/desktop/我的文件夹1/我的文件夹2"];

       

        NSError * error = nil;

        if ([managercreateDirectoryAtPath:DirectoryPathwithIntermediateDirectories:NOattributes:nilerror:&error] != YES) {

//            NSString * str = [error localizedDescription];

            NSLog(@"创建失败");

        }else {

//            NSString * str = [error localizedDescription];

            NSLog(@"创建成功");

        }





若此处为NO,则中间:我的文件夹1(不论之前存不存在) 都不创建,之前也不存在。


运行结果 

2015-04-11 11:30:41.477 2.创建文件夹[852:537431]创建失败

Program ended with exit code: 0


    若此处为YES,则中间:我的文件夹1(不论之前存不存在)都创建,及时之间不存在

运行结果(创建出一个文件夹 我的文件夹1 他下面 我的文件夹2)

2015-04-11 11:38:11.547 2.创建文件夹[877:577493]创建成功

Program ended with exit code: 0





文件重命名的两个方法:

方法一、思路:1.提取原有文件data,

2.将data存入新建的文件,

  3.删除原有文件


方法二、用[manager moveItemAtPath:filePathtoPath:newPath error:nil];方法将filepath

路径下的文件名换成newPath


对文件NSData赋值,在文件内将内容更改后,move后的文件内容保持跟最后修改的一致

如果文件NSdata未赋值,在程序外文件内更改,move后新文件仍为空。










综合练习:

新建一个文件夹,将文件夹外面的文件移动到文件夹内部,并复制一副本


1.怎么新建oc文件夹

2.文件的移动

3.文件的复制


#import <Foundation/Foundation.h>


int main(int argc,const char * argv[]) {

    @autoreleasepool {

      

        // 文件管理者

        NSFileManager * manager = [NSFileManagerdefaultManager];

        

        // 文件夹地址

        NSString * directorPath = [NSHomeDirectory()stringByAppendingPathComponent:@"desktop/Goods"];

        // 文件地址

        NSString * filePath = [NSHomeDirectory()stringByAppendingPathComponent:@"desktop/east.txt"];

         NSString * filePath2 = [NSHomeDirectory()stringByAppendingPathComponent:@"desktop/Goods/east.txt"];

        // 文件数据

        NSString * strForData = @"Goods is selling good!";

        NSData * dataForFile = [strForDatadataUsingEncoding:NSUTF8StringEncoding];

        

        if ([managercreateDirectoryAtPath:directorPath withIntermediateDirectories:YESattributes:nilerror:nil]) {

            NSLog(@"创建成功");

        }

        if ([manager fileExistsAtPath:filePath]) {

            NSLog(@"文件存在");

        }else{

            

        [manager createFileAtPath:filePathcontents:dataForFile attributes:nil];

            NSLog(@"文件创建成功!");

        }


        if ([manager moveItemAtPath:filePath toPath:filePath2error:nil]) {

            NSLog(@"移动成功");

        }else{

            NSLog(@"移动失败");

        }

        

         NSString * filePath3 = [NSHomeDirectory()stringByAppendingPathComponent:@"desktop/Goods/1east.txt"];

        // copy

        if ([manager copyItemAtPath:filePath2 toPath:filePath3error:nil]) {

            NSLog(@"success");

        }else

            NSLog(@"fail");

        }

        

    }

    return 0;

}

0 0
原创粉丝点击