ios NSFileManager創建目錄、文件


NSFileManager *fileManager = [NSFileManager defaultManager];        
NSString *str1 = NSHomeDirectory();
_filePath = [[NSString stringWithFormat:@"%@/Documents/imageViews/test.plist",str1]retain];
        
 NSLog(@"%@",_filePath);
  if(![fileManager fileExistsAtPath:_filePath]){//如果不存在,則說明是第一次運行這個程序,那么建立這個文件夾
    NSLog(@"first run");
      NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
      NSString *directryPath = [path stringByAppendingPathComponent:@"imageViews"];
       [fileManager createDirectoryAtPath:directryPath withIntermediateDirectories:YES attributes:nil error:nil];
       NSString *filePath = [directryPath stringByAppendingPathComponent:@"test.plist"];
      NSLog(@"%@",filePath);
      [fileManager createFileAtPath:filePath contents:nil attributes:nil];
.........
 }

此段代碼創建的filePath為

/Users/yuqiu/Library/Application Support/iPhone Simulator/6.1/Applications/2A8EFE9E-4CCA-41D1-8A5F-1FF00A115FA3/Documents/imageViews/test.plist
 

一、創建~/Documents/imageViews/test.plist的詳細步驟

     1、找到Documetnts目錄所在的位置  

NSString *str1 = NSHomeDirectory();

str1為/Users/yuqiu/Library/Application Support/iPhone Simulator/6.1/Applications/2A8EFE9E-4CCA-41D1-8A5F-1FF00A115FA3

    2、加上Documetnts這層目錄

 NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

path為/Users/yuqiu/Library/Application Support/iPhone Simulator/6.1/Applications/2A8EFE9E-4CCA-41D1-8A5F-1FF00A115FA3/Documents
注意:使用的是stringByAppendingPathComponent:方法,不需要加“/";  如果用的是別的方法加的話,需要寫成@"/Documents".

 

ps:這里1、2兩步可以簡化為

NSArray *paths = NSSearchPathForDerictoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path = [paths lastObject];

 

    3、在Documetnts目錄中創建名為imageViews的目錄

NSFileManager *fileManager = [NSFileManager defaultManager];      
NSString *directryPath = [path stringByAppendingPathComponent:@"imageViews"];
[fileManager createDirectoryAtPath:directryPath withIntermediateDirectories:YES attributes:nil error:nil];

創建NSFileManager的實例fileManager.NSFileManager這個類是專門進行文件管理的,可以創建文件,目錄,刪除,遍歷目錄等。我們調用了 createDirectoryAtPath:方法創建了一個新目錄。

    4、在imageViews目錄里,創建文件test.plist.

NSString *filePath = [directryPath stringByAppendingPathComponent:@"test.plist"];
[fileManager createFileAtPath:filePath contents:nil attributes:nil];

   調用createFileAtPath:創建文件
   最后得到的整個文件路徑為:

 

二、NSFileManager常用的文件管理操作

     1、創建目錄  createDirectoryAtPath:

     2、創建文件  createFileAtPath:

     3、刪除某個文件  removeItemAtPath:

     4、檢查某個文件是否存在  fileExistsAtPath: 

     5、檢查文件是否可讀 isReadableFileAtPath:

          是否可寫:isWritableFileAtPath:

      6、取得文件屬性  fileAttributesAtPath:

          改變文件屬性changeAttributesAtPath:

      7、從path代表的文件中讀取數據:contentsAtPath

      8、移動文件movePath:toPath:handler:

      9、復制文件copyPath:toPath:handler:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM