NSfileManager的使用方法

cmn6 9年前發布 | 4K 次閱讀 Objective-C IOS

總結了一下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");

 本文由用戶 cmn6 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!