NSfileManager的使用方法

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

总结了一下NSFileManager的一些常用方法,


    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask,YES);

   NSString *documentDirectory = [paths objectAtIndex:];

   NSLog(@"%@", documentDirectory);//路径查看

    

     //1.创建文件夹

    NSFileManager *fileManager = [NSFileManagerdefaultManager];

   NSString *testDirectory = [documentDirectory stringByAppendingPathComponent:@"testbug1"];//创建文件夹

    //创建目录

    [fileManager createDirectoryAtPath:testDirectorywithIntermediateDirectories:YESattributes:nilerror:nil];

    

    

    

    

    //2.创建文件

   NSString *test11 = [testDirectory stringByAppendingPathComponent:@"test111.txt"];

   NSString *test22 = [testDirectory stringByAppendingPathComponent:@"test222.txt"];

   NSString *string = @"写入内容1";

    [fileManager createFileAtPath:test11contents:[string dataUsingEncoding:NSUTF8StringEncoding]attributes:nil];

    [fileManager createFileAtPath:test22contents:[string dataUsingEncoding:NSUTF8StringEncoding]attributes:nil];

    

    //3.查看Document里所有文件

   NSArray *files = [fileManager subpathsAtPath:documentDirectory];

    //4.查看目录里所有子文件

   NSArray *subfiles = [fileManager subpathsAtPath:testDirectory];

   NSLog(@"%@", subfiles);

   NSLog(@"%@", files);

    

    

    //5.更改到待操作的到目录下

    [fileManager changeCurrentDirectoryPath:[documentDirectorystringByExpandingTildeInPath]];

    //创建文件filename文件名,contents文件的内容

    NSString *fileName =@"testfilemanager.txt";

    NSArray *array = [[NSArrayalloc]initWithObjects:@"hello world",@"hello World", nil];


    [fileManagercreateFileAtPath:fileName contents:array attributes:nil];

    

    //6.删除文件

    [fileManagerremoveItemAtPath:fileName error:nil];

    //7.复制文件后者给前者

   NSError *error;

    [fileManagercopyItemAtPath:test11 toPath:test22 error:&error];

    //8.移动文件

   NSString *test33 = [documentDirectory stringByAppendingPathComponent:@"test33.txt"];

   if ([fileManager moveItemAtPath:test11toPath:test33 error:&error] !=YES) {

        NSLog(@"111%@", [errorlocalizedDescription]);

    }

    //9.文件是否存在

    if ([[NSFileManagerdefaultManager]fileExistsAtPath:@"/Users/dlios/Library/Application Support/iPhone Simulator/7.1/Applications/AC7B8788-BDCB-43AC-ABB6-8E9676CF94DC/Documents/testbug/test22333.txt"]) {

       NSLog(@"yes");

    }

   else NSLog(@"no");