//對於錯誤資訊 NSError *error; // 建立檔案管理工具 NSFileManager *fileMgr = [NSFileManager defaultManager]; //指向檔案目錄 NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; //建立一個目錄 [[NSFileManager defaultManager] createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] withIntermediateDirectories:YES attributes:nil error:&error]; /** < 建立一個檔案*/ // File we want to create in the documents directory我們想要建立的檔案將會出現在檔案目錄中 // Result is: /Documents/file1.txt結果為:/Documents/file1.txt NSString *filePath= [documentsDirectory stringByAppendingPathComponent:@"file1.txt"]; //需要寫入的字串 NSString *str= @"iPhoneDeveloper Tips\nhttp://iPhoneDevelopTips,com"; //寫入檔案 [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; //顯示檔案目錄的內容 NSLog(@"Documentsdirectory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]); /** < 對一個檔案重新命名*/ //通過移動該檔案對檔案重新命名 NSString *filePath2= [documentsDirectory stringByAppendingPathComponent:@"file2.txt"]; //判斷是否移動 if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES) NSLog(@"Unable to move file: %@", [error localizedDescription]); //顯示檔案目錄的內容 NSLog(@"Documentsdirectory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]); /** < 刪除一個檔案*/ //在filePath2中判斷是否刪除這個檔案 if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES) NSLog(@"Unable to delete file: %@", [error localizedDescription]); //顯示檔案目錄的內容 NSLog(@"Documentsdirectory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]); /** < 擷取一個目錄內的檔案及資料夾清單*/ NSFileManager *fileManager = [NSFileManager defaultManager]; //在這裡擷取應用程式Documents檔案夾裡的檔案及資料夾清單 NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDir = [documentPaths objectAtIndex:0]; NSError *error2 = nil; NSArray *fileList = [[NSArray alloc] init]; //fileList便是包含有該檔案夾下所有檔案的檔案名稱及檔案夾名的數組 fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error2]; /** < 列出給定一個檔案夾裡的所有子檔案夾名*/ NSMutableArray *dirArray = [[NSMutableArray alloc] init]; BOOL isDir = NO; //在上面那段程式中獲得的fileList中列出檔案夾名 for (NSString *file in fileList) { NSString *path = [documentDir stringByAppendingPathComponent:file]; [fileManager fileExistsAtPath:path isDirectory:(&isDir)]; if (isDir) { [dirArray addObject:file]; } isDir = NO; } NSLog(@"Every Thing in the dir:%@",fileList); NSLog(@"All folders:%@",dirArray);