NSFileManager可以安全地在多個線程中調用。然而,如果你使用一個delegate來接收move,copy,remove,and link操作的通知,你應該創建一個唯一的file manager 對象的實例(使用init方法創建一個fileManager而非defaultManager),指定你的代理到這個對象,并使用這個file manager來初始化你的操作。
首先你找到自己的程序的目錄: NSHomeDirectory() ,目錄結構為:
Documents(NSDocumentDirectory) //用于寫入應用相關數據文件的目錄,在ios中寫入這里的文件能夠與iTunes共享并訪問,存儲在這里的文件會自動備份到云端
Library/Caches(NSCachesDirectory) //用于寫入應用支持文件的目錄,保存應用程序再次啟動需要的信息。iTunes不會對這個目錄的內容進行備份
tmp(use NSTemporaryDirectory()) //這個目錄用于存放臨時文件,只程序終止時需要移除這些文件,當應用程序不再需要這些臨時文件時,應該將其從這個目錄中刪除
Library/Preferences //這個目錄包含應用程序的偏好設置文件,使用 NSUserDefault類進行偏好設置文件的創建、讀取和修改
//獲取Documents文件夾目錄,第一個參數是說明獲取Doucments文件夾目錄,第二個參數說明是在當前應用沙盒中獲取,所有應用沙盒目錄組成一個數組結構的數據存放
NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [docPath objectAtIndex:0];
NSLog(@"Documents目錄:%@",documentsPath);
//獲取Cache目錄
NSArray *cacPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [cacPath objectAtIndex:0];
NSLog(@"Cache目錄:%@",cachePath);
//Library目錄
NSArray *libsPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *libPath = [libsPath objectAtIndex:0];
NSLog(@"Library目錄:%@",libPath);
//temp目錄
NSString *tempPath = NSTemporaryDirectory();
NSLog(@"temp目錄:%@",tempPath);
常見的NSFileManager文件方法
-(NSData *)contentsAtPath:path //從一個文件讀取數據
-(BOOL)createFileAtPath: path contents:(NSData *)data attributes:attr //向一個文件寫入數據(能否寫入由其attributes決定)
-(BOOL)removeItemAtPath:path error:err //刪除一個文件
-(BOOL)moveItemAtPath:from toPath:to error:err //重命名或者移動一個文件(to不能是已存在的)
-(BOOL)copyItemAtPath:from toPath:to error:err //復制文件(to不能是已存在的)
-(BOOL)contentsEqualAtPath:path andPath:path2 //比較兩個文件的內容
-(BOOL)fileExistAtPath:path //測試文件是否存在
-(BOOL)isReadableFileAtPath:path //測試文件是否存在,并且是否能執行讀操作
-(BOOL)isWriteableFileAtPath:path //測試文件是否存在,并且是否能執行寫操作
-(NSDictionary *)attributesOfItemAtPath:path error:err //獲取文件的屬性
-(BOOL)setAttributesOfItemAtPath:attr error:err //更改文件的屬性
NSFileManager使用示例:
1、文件的創建
-(IBAction) CreateFile
{
NSError *error; //對于錯誤信息
// 創建文件管理器
NSFileManager *fileMgr = [NSFileManager defaultManager];
//指向文件目錄
NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
//創建一個目錄
[[NSFileManager defaultManager] createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] attributes:nil];
注意:創建了我們想要文件目錄,若想寫入數據則需在路徑后拼接上文件名。 若未拼接文件名直接寫入數據會失敗(因為創建的是一個文件夾)
NSString *filePath= [documentsDirectory stringByAppendingPathComponent:@"file2.txt"];
//需要寫入的字符串
NSString *str= @"iPhoneDeveloper Tips\nhttp://iPhoneDevelopTips,com";
//寫入文件
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
//顯示文件目錄的內容
NSLog(@"Documentsdirectory: %@",[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
}
2、對文件重命名
想要重命名一個文件,我們需要把文件移到一個新的路徑下。下面的代碼創建了我們所期望的目標文件的路徑,然后請求移動文件以及在移動之后顯示文件目錄。
//通過移動該文件對文件重命名
NSString *filePath2= [documentsDirectory
stringByAppendingPathComponent:@"file2.txt"];
//判斷是否移動
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
{
NSLog(@"Unable to move file: %@", [error localizedDescription]);
}else{
//顯示文件目錄的內容
NSLog(@"Documentsdirectory: %@",[fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);
}
注意:切記重命名或者移動一個文件(to不能是已存在的)
3、刪除一個文件
為了使這個技巧完整,讓我們再一起看下如何刪除一個文件:
//在filePath2中判斷是否刪除這個文件
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES){
NSLog(@"Unable to delete file: %@", [error localizedDescription]);
}else{
//顯示文件目錄的內容
NSLog(@"Documentsdirectory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);
}
4、刪除目錄下所有文件
//獲取文件路徑
- (NSString *)attchmentFolder{
NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [document stringByAppendingPathComponent:@"Attchments"];
NSFileManager *manager = [NSFileManager defaultManager];
if(![manager contentsOfDirectoryAtPath:path error:nil]){
[manager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
}
return path;
}
--清除附件
BOOL result = [[NSFileManager defaultManager] removeItemAtPath:[[MOPAppDelegate instance] attchmentFolder] error:nil];
5、判斷文件是否存在
NSString *filePath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.plist"];
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath])
{
//do some thing
}
NSFileManager 的方法
發現文件夾內容:
– contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:
– contentsOfDirectoryAtPath:error:
– enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:
– enumeratorAtPath:
– mountedVolumeURLsIncludingResourceValuesForKeys:options:
– subpathsOfDirectoryAtPath:error:
– subpathsAtPath:
創建和刪除items:
– createDirectoryAtURL:withIntermediateDirectories:attributes:error:
– createDirectoryAtPath:withIntermediateDirectories:attributes:error:
– createFileAtPath:contents:attributes:
– removeItemAtURL:error:
– removeItemAtPath:error:
– replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error:
移動和拷貝 Items
– copyItemAtURL:toURL:error:
– copyItemAtPath:toPath:error:
– moveItemAtURL:toURL:error:
– moveItemAtPath:toPath:error:
Determining Access to Files
– fileExistsAtPath:
– fileExistsAtPath:isDirectory:
– isReadableFileAtPath:
– isWritableFileAtPath:
– isExecutableFileAtPath:
– isDeletableFileAtPath:
Getting and Setting Attributes
– componentsToDisplayForPath:
– displayNameAtPath:
– attributesOfItemAtPath:error:
– attributesOfFileSystemForPath:error:
– setAttributes:ofItemAtPath:error:
Getting and Comparing File Contents
– contentsAtPath:
– contentsEqualAtPath:andPath:
Converting File Paths to Strings
– fileSystemRepresentationWithPath:
– stringWithFileSystemRepresentation:length:
Managing the Delegate
– setDelegate:
– delegate
Managing the Current Directory
– changeCurrentDirectoryPath:
– currentDirectoryPath
NSFileManager 的代理
Moving an Item
– fileManager:shouldMoveItemAtURL:toURL:
– fileManager:shouldMoveItemAtPath:toPath:
– fileManager:shouldProceedAfterError:movingItemAtURL:toURL:
– fileManager:shouldProceedAfterError:movingItemAtPath:toPath:
Copying an Item
– fileManager:shouldCopyItemAtURL:toURL:
– fileManager:shouldCopyItemAtPath:toPath:
– fileManager:shouldProceedAfterError:copyingItemAtURL:toURL:
– fileManager:shouldProceedAfterError:copyingItemAtPath:toPath:
Removing an Item
– fileManager:shouldRemoveItemAtURL:
– fileManager:shouldRemoveItemAtPath:
– fileManager:shouldProceedAfterError:removingItemAtURL:
– fileManager:shouldProceedAfterError:removingItemAtPath:
Linking an Item
– fileManager:shouldLinkItemAtURL:toURL:
– fileManager:shouldLinkItemAtPath:toPath:
– fileManager:shouldProceedAfterError:linkingItemAtURL:toURL:
– fileManager:shouldProceedAfterError:linkingItemAtPath:toPath:
常用路徑工具函數
NSString * NSUserName(); 返回當前用戶的登錄名
NSString * NSFullUserName(); 返回當前用戶的完整用戶名
NSString * NSHomeDirectory(); 返回當前用戶主目錄的路徑
NSString * NSHomeDirectoryForUser(); 返回用戶user的主目錄
NSString * NSTemporaryDirectory(); 返回可用于創建臨時文件的路徑目錄
常用路徑工具方法
-(NSString *)pathWithComponents:components 根據components(NSArray對象)中元素構造有效路徑
-(NSArray *) pathComponents 析構路徑,獲取路徑的各個部分
-(NSString *)lastPathComponent 提取路徑的最后一個組成部分
-(NSString *)pathExtension 路徑擴展名
-(NSString *)stringByAppendingPathComponent:path 將path添加到現有路徑末尾
-(NSString *)stringByAppendingPathExtension:ext 將拓展名添加的路徑最后一個組成部分
-(NSString *)stringByDeletingPathComponent 刪除路徑的最后一個部分
-(NSString *)stringByDeletingPathExtension 刪除路徑的最后一個部分 的擴展名
-(NSString *)stringByExpandingTildeInPath 將路徑中的代字符擴展成用戶主目錄(~)或指定用戶主目錄(~user)
-(NSString *)stringByResolvingSymlinksInPath 嘗試解析路徑中的符號鏈接
-(NSString *)stringByStandardizingPath 通過嘗試解析~、..、.、和符號鏈接來標準化路徑
使用路徑NSPathUtilities.h
tempdir = NSTemporaryDirectory(); 臨時文件的目錄名
path = [fm currentDirectoryPath]; 獲取當前目錄
[path lastPathComponent]; 從路徑中提取最后一個文件名
fullpath = [path stringByAppendingPathComponent:fname]; 將文件名附加到路勁的末尾
extenson = [fullpath pathExtension]; 路徑名的文件擴展名
homedir = NSHomeDirectory(); 用戶的主目錄
component = [homedir pathComponents]; 路徑的每個部分
NSProcessInfo類:允許你設置或檢索正在運行的應用程序的各種類型信息
(NSProcessInfo *)processInfo 返回當前進程的信息
-(NSArray*)arguments 以NSString對象數字的形式返回當前進程的參數
-(NSDictionary *)environment 返回變量/值對詞典。描述當前的環境變量
-(int)processIdentity 返回進程標識
-(NSString *)processName 返回進程名稱
-(NSString *)globallyUniqueString 每次調用該方法都會返回不同的單值字符串,可以用這個字符串生成單值臨時文件名
-(NSString *)hostname 返回主機系統的名稱
-(unsigned int)operatingSystem 返回表示操作系統的數字
-(NSString *)operatingSystemName 返回操作系統名稱
-(NSString *)operatingSystemVersionString 返回操作系統當前版本
-(void)setProcessName:(NSString *)name 將當前進程名稱設置為name
NSFileHandle類允許更有效地使用文件。
可以實現如下功能:
1、打開一個文件,執行讀、寫或更新(讀寫)操作;
2、在文件中查找指定位置;
3、從文件中讀取特定數目的字節,或將特定數目的字節寫入文件中
另外,NSFileHandle類提供的方法也可以用于各種設備或套接字。一般而言,我們處理文件時都要經歷以下三個步驟:
1、打開文件,獲取一個NSFileHandle對象(以便在后面的I/O操作中引用該文件)。
2、對打開文件執行I/O操作。
3、關閉文件。
NSFileHandle *fileHandle = [[NSFileHandle alloc]init];
//打開一個文件準備讀取
fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];
// 從設備或者通道返回可用的數據
fileData = [fileHandle availableData];
fileData = [fileHandle readDataToEndOfFile];
//將NSData數據寫入文件
[fileHandle writeData:fileData];
//關閉文件 ... ...
[fileHandle closeFile];
注:NSFileHandle類沒有提供創建文件的功能,所以必須使用NSFileManager來創建文件