ios檔案和檔案夾管理

來源:互聯網
上載者:User


獲得磁碟上最熱門檔案夾的路徑

我們知道,蘋果上的應用程式都是運行在自己的沙箱中的,很少也沒有足夠的許可權跟沙箱外面的檔案資源打交道,一般一個應用的檔案目錄如下:


想要獲得應用目錄下的檔案夾路徑最常用的操作:

NSFileManager類的URLsFZ喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vckRpcmVjdG9yeTppbkRvbWFpbnM6IMq1wP23vbeo1MrQ7cTj1NpJT1O1xM7EvP7Ptc2z1tDL0cv31ri2qLXExL/CvCzM2LHwysfU2sTj06bTw7XEybPP5NbQLrTLt723qNPQwb249rLOyv2juiA8L3A+CjxwPjwvcD4KPHAgY2xhc3M9"p1">URLsForDirectory:

此參數是你將要搜尋的字典對象.為此參數傳遞一個NSSearchPath類型的目錄字典.我將在稍後詳細討論此參數.

inDomains:

此參數指定你在哪兒搜尋給定的目錄.此參數必須是一NSSearchDomainMask的枚舉值.

假設你要獲得你應用的 Document 檔案夾路徑,你會發現是如此簡單:

 NSFileManager *fileManager = [[NSFileManager alloc] init];    NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];    if ([urls count] > 0) {        NSURL *documentsFolder = urls[0];        NSLog(@"%@",documentsFolder);    }else{        NSLog(@"Could not find the Documents folder");    }

下面是 NSFileManager 類執行個體方法 URLsForDirectory:inDomains:的所有你可以傳遞的重要參數值:

URLsForDirectory

NSLibraryDirectory 標記應用的library檔案夾.

NSCachesDirectory 標記caches檔案夾,在之前解釋說明過.

NSDocumentDirectory 標記document檔案夾.

inDomains

NSUserDomainMask 標記對檔案夾路徑的搜尋在目前使用者檔案夾下進行.在OS X中,此檔案夾為~/.

如果你想獲得 tmp 檔案夾的路徑,請像這樣使用 C 函數 NSTemporaryDirectory( );

NSString *tempDirectory = NSTemporaryDirectory();        NSLog(@"Temp Directory = %@",tempDirectory);

對檔案進行讀寫操作
//寫-(BOOL)writeText:(NSString *)paramText toPath:(NSString *)paramPath{    return [paramText writeToFile:paramPath atomically:YES encoding:NSUTF8StringEncoding error:nil];}

//讀-(NSString *)readTextFromPath:(NSString *)paramPath{    return [[NSString alloc] initWithContentsOfFile:paramPath encoding:NSUTF8StringEncoding error:nil];}

- (void)viewDidLoad{    [super viewDidLoad];    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"MyFile.txt"];    if ([self writeText:@"Hello,World!" toPath:filePath]) {        NSString *readText = [self readTextFromPath:filePath];        if ([readText length]) {            NSLog(@"Text read from disk = %@",readText);        }else{            NSLog(@"Failed to read the text from disk");        }    }else{        NSLog(@"Failed to write the file");    }}


以數組的形式保持到檔案:
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"MyFile.txt"];    NSArray *arrayOfNames = @[@"Steve",@"John",@"Aaron"];    if ([arrayOfNames writeToFile:filePath atomically:YES]) {        NSArray *readArray = [[NSArray alloc] initWithContentsOfFile:filePath];        if ([readArray count]) {            NSLog(@"Read the array back from disk just fine");        }else{            NSLog(@"Failed to read the array back from disk");        }    }else{        NSLog(@"Failed to save the array to disk");    }

NSArray類的執行個體方法writeToFile:atomiclly只能儲存包含如下物件類型的數組:

NSString

NSDictionary

NSArray

NSData

NSNumber

NSDate

如果你試圖在數組中插入其他的對象,則資料將無法被儲存到磁碟。


字典具有和數組類似的進行資料寫磁碟及讀資料回字典對象的方式.方法名稱也完全 相同,且數組的儲存規則同樣適用於字典

    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"MyFile.txt"];    NSDictionary *dict = @{@"firstName": @"Aaron",                           @"lastName":@"zheng",                           @"age":@"21"};    if ([dict writeToFile:filePath atomically:YES]) {        NSDictionary *readDictionary = [[NSDictionary alloc] initWithContentsOfFile:filePath];        if ([readDictionary isEqualToDictionary:dict]) {            NSLog(@"The file we read is the same one as the one we saved");        }else{            NSLog(@"Failed to read the dictionary from disk");        }    }else{        NSLog(@"Failed to write the dictionay to disk");    }


在磁碟中建立一個檔案夾:

//在磁碟中建立一個檔案夾-(void)createDirectory{    NSFileManager *fileManager = [[NSFileManager alloc] init];    NSString *tempDir = NSTemporaryDirectory();    NSString *path = [tempDir stringByAppendingPathComponent:@"images"];        NSError *error;    if ([fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {        NSLog(@"Successfully created the directory");    }else{        NSLog(@"Failed to create the directory , ERROR = %@",error);    }}

上面的 withIntermediateDirectories:YES 參數設定為YES,則在建立最深層檔案夾的時候,若父資料夾不存在,系統會直接幫你建立好。
刪除檔案及檔案夾

//刪除檔案及檔案夾-(void)removeDir{    NSFileManager *fileManager = [[NSFileManager alloc] init];    NSString *tempDir = NSTemporaryDirectory();    NSString *path = [tempDir stringByAppendingString:@"images"];        NSError *error;    if([fileManager removeItemAtPath:path error:&error] == NO){        NSLog(@"Failed to remove path %@, ERROR = %@",path,error);    }    }

好了,就先寫到這裡吧,,不想寫了,有時間在寫寫關於磁碟中檔案的安全處理,附註:文中的樣本都是摘自《ios 6 Programming Cookbook》一書,由DevDiv網友自發組織翻譯,支援技術和資訊的共用!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.