1、常見的NSFileManager文件方法
-(NSData *)contentsAtPath:path //從一個文件讀取數據
-(BOOL)createFileAtPath: path contents:(NSData *)data attributes:attr //向一個文件寫入數據
-(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 //測試文件是否存在为黎,并且是否能執(zhí)行讀操作
-(BOOL)isWriteableFileAtPath:path //測試文件是否存在铭乾,并且是否能執(zhí)行寫操作
-(NSDictionary *)attributesOfItemAtPath:path error:err //獲取文件的屬性
-(BOOL)setAttributesOfItemAtPath:attr error:err //更改文件的屬性
2.使用目錄
-(NSString *)currentDirectoryPath //獲取當前目錄
-(BOOL)changeCurrentDirectoryPath:path //更改當前目錄
-(BOOL)copyItemAtPath:from toPath:to error:err //復制目錄結構(to不能是已存在的)
-(BOOL)createDirectoryAtPath:path withIntermediateDirectories:(BOOL)flag attribute:attr //創(chuàng)建一個新目錄
-(BOOL)fileExistAtPath:path isDirectory:(BOOL*)flag //測試文件是不是目錄(flag中儲存結果YES/NO)
-(NSArray *)contentsOfDirectoryAtPath:path error:err //列出目錄內容
-(NSDirectoryEnumerator *)enumeratorAtPath:path //枚舉目錄的內容
-(BOOL)removeItemAtPath:path error:err //刪除空目錄
-(BOOL)moveItemAtPath:from toPath:to error:err //重命名或移動一個目錄(to不能是已存在的)
3炕檩、常用路徑工具方法
+(NSString *)pathWithComponens:components //根據components中的元素構造有效路徑
-(NSArray *)pathComponents //析構路徑笛质,獲得組成此路徑的各個部分
-(NSString *)lastPathComponent //提取路徑的最后一個組成部分
-(NSString *)pathExtension //從路徑的最后一個組成部分中提取其擴展名
-(NSString *)stringByAppendingPathComponent:path //將path添加到現(xiàn)有路徑的末尾
-(NSString *)stringByAppendingPathExtension:ext //將指定的擴展名添加到路徑的最后一個組成部分
-(NSString *)stringByDeletingLastPathComponent //刪除路徑的最后一個組成部分
-(NSString *)stringByDeletingPathExtension //從文件的最后一部分刪除擴展名
-(NSString *)stringByExpandingTileInPath //將路徑中代字符擴展成用戶主目錄(<sub>)或指定用戶的主目錄(</sub>user)
-(NSString *)stringByresolvingSymlinksInPath //嘗試解析路徑中的符號鏈接
-(NSString *)stringByStandardizingPath //通過嘗試解析~妇押、..(父目錄符號)敲霍、.(當前目錄符號)和符號鏈接來標準化路徑
4、常用的路徑工具函數
NSString* NSUserName(void) //返回當前用戶的登錄名
NSString* NSFullUserName(void) //返回當前用戶的完整用戶名
NSString* NSHomeDirectory(void) //返回當前用戶主目錄的路徑
NSString* NSHomeDirectoryForUser(NSString* user) //返回用戶user的主目錄
NSString* NSTemporaryDirectory(void) //返回可用于創(chuàng)建臨時文件的路徑目錄
5潭袱、常用的IOS目錄
Documents(NSDocumentDirectory) //用于寫入應用相關數據文件的目錄锋恬,在ios中寫入這里的文件能夠與iTunes共享并訪問与学,存儲在這里的文件會自動備份到云端
Library/Caches(NSCachesDirectory) //用于寫入應用支持文件的目錄,保存應用程序再次啟動需要的信息晕窑。iTunes不會對這個目錄的內容進行備份
tmp(use NSTemporaryDirectory()) //這個目錄用于存放臨時文件杨赤,只程序終止時需要移除這些文件截汪,當應用程序不再需要這些臨時文件時衙解,應該將其從這個目錄中刪除
Library/Preferences //這個目錄包含應用程序的偏好設置文件,使用 NSUserDefault類進行偏好設置文件的創(chuàng)建舌剂、讀取和修改
IOS文件操作的兩種方式:NSFileManager操作和流操作
1霍转、文件的創(chuàng)建
-(IBAction) CreateFile{
**//對于錯誤信息**
NSError *error;
**// 創(chuàng)建文件管理器**
NSFileManager *fileMgr = [NSFileManager defaultManager];
**//指向文件目錄**
NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
**//創(chuàng)建一個目錄**
[[NSFileManager defaultManager] createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] attributes:nil];
**// File we want to create in the documents directory我們想要創(chuàng)建的文件將會出現(xiàn)在文件目錄中**
// Result is: /Documents/file1.txt結果為:/Documents/file1.txt
NSString *filePath= [documentsDirectory
stringByAppendingPathComponent:@"file2.txt"];
**//需要寫入的字符串**
NSString *str= @"iPhoneDeveloper Tips [http://iPhoneDevelopTips,com](https://links.jianshu.com/go?to=http%3A%2F%2FiPhoneDevelopTips%2Ccom)";
**//寫入文件**
[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
**//顯示文件目錄的內容**
NSLog(@"Documentsdirectory: contentsOfDirectoryAtPath:documentsDirectory error:&error]);
}
2避消、對文件重命名
對一個文件重命名
想要重命名一個文件沾谓,我們需要把文件移到一個新的路徑下均驶。下面的代碼創(chuàng)建了我們所期望的目標文件的路徑妇穴,然后請求移動文件以及在移動之后顯示文件目錄爬虱。
//通過移動該文件對文件重命名
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:documentsDirectoryerror:&error]);
3、刪除一個文件
為了使這個技巧完整瞒滴,讓我們再一起看下如何刪除一個文件:
//在filePath2中判斷是否刪除這個文件
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)
NSLog(@"Unable to delete file: %@", [error localizedDescription]);
//顯示文件目錄的內容 NSLog(@"Documentsdirectory: %@",
[fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);
一旦文件被刪除了妓忍,正如你所預料的那樣世剖,文件目錄就會被自動清空:
這些示例能教你的,僅僅只是文件處理上的一些皮毛祖凫。想要獲得更全面惠况、詳細的講解粱年,你就需要掌握NSFileManager文件的知識台诗。
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];
IPhone中獲取文件各項屬性方法
-(NSData *)applicationDataFromFile:(NSString *)fileName
{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory =[paths objectAtIndex:0];
NSString *appFile =[documentsDirectory stringByAppendingPathComponent:fileName];
NSData *data =[[[NSData alloc]initWithContentsOfFile:appFile]autorelease];
return data;
}
-(void)getFileAttributes
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *path = @"/1ct.rtf";
NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:path traverseLink:YES];
NSLog(@"@@");
if (fileAttributes != nil) {
NSNumber *fileSize;
NSString *fileOwner, *creationDate;
NSDate *fileModDate;
//NSString *NSFileCreationDate
//文件大小
if (fileSize = [fileAttributes objectForKey:NSFileSize]) {
NSLog(@"File size: %qi ", [fileSize unsignedLongLongValue]);
}
//文件創(chuàng)建日期
if (creationDate = [fileAttributes objectForKey:NSFileCreationDate]) {
NSLog(@"File creationDate: %@ ", creationDate);
//textField.text=NSFileCreationDate;
}
//文件所有者
if (fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName]) {
NSLog(@"Owner: %@ ", fileOwner);
}
//文件修改日期
if (fileModDate = [fileAttributes objectForKey:NSFileModificationDate]) {
NSLog(@"Modification date: %@ ", fileModDate);
}
}
else {
NSLog(@"Path (%@) is invalid.", path);
}
}
///////////////////
文件類型粱快,文件縮略圖呢事哭?鳍咱?谤辜?
============================
//獲取當前應用程序的主目錄 NSString directoryPath =NSHomeDirectory();
//獲取當前目錄下的所有文件 NSArray directoryContents = [[NSFileManager defaultManager] directoryContentsAtPath: directoryPath];
//獲取一個文件或文件夾 NSString selectedFile = (NSString)[directoryContents objectAtIndex: indexPath.row];
//拼成一個完整路徑 [directoryPath stringByAppendingPathComponent: selectedFile];
BOOL isDir;
//判斷是否是為目錄
if ([[NSFileManager defaultManager] fileExistsAtPath:selectedPath isDirectory:&isDir] && isDir)
{//目錄
}
else
{//文件
}
//日期格式化 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
//數字格式化
NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat: @"#,##0.## bytes"];
//獲取文件屬性
NSDictionary *fileAttributes =[[NSFileManager defaultManager] fileAttributesAtPath: directoryPath traverseLink: YES];
//獲取文件的創(chuàng)建日期
NSDate modificationDate = (NSDate)[fileAttributes objectForKey: NSFileModificationDate];
//獲取文件的字節(jié)大小
NSNumber fileSize = (NSNumber)[fileAttributes objectForKey: NSFileSize];
//格式化文件大小 nsstring A = [numberFormatter stringFromNumber: fileSize];
//格式化文件創(chuàng)建日期
NSstring B =[dateFormatter stringFromDate: modificationDate];
[numberFormatter release];
[dateFormatter release];
//讀取文件內容操作- (void) loadFileContentsIntoTextView{ //通過流打開一個文件 NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath: filePath]; [inputStream open];
NSInteger maxLength = 128;
uint8_t readBuffer [maxLength];
//是否已經到結尾標識
BOOL endOfStreamReached = NO;
// NOTE: this tight loop will block until stream ends
while (! endOfStreamReached)
{
NSInteger bytesRead = [inputStream read: readBuffer maxLength:maxLength];
if (bytesRead == 0)
{//文件讀取到最后
endOfStreamReached = YES;
}
else if (bytesRead == -1)
{//文件讀取錯誤
endOfStreamReached = YES;
}
else
{
NSString *readBufferString =[[NSString alloc] initWithBytesNoCopy: readBuffer length: bytesRead encoding: NSUTF8StringEncoding freeWhenDone: NO];
//將字符不斷的加載到視圖
[self appendTextToView: readBufferString];
[readBufferString release];
}
}
[inputStream close];
[inputStream release];
}
異步文件的讀取 涡戳,在網絡方面渔彰,由于網絡的不可靠性可能會造成NSFileManager的文件操作方法的阻塞推正,而以流的方式進行操作則可以實現(xiàn)異步的讀取舔稀。
NSStream是可以異步工作的内贮。可以注冊一個在流中有字節(jié)可讀的時候回調的函數什燕,如果沒有可讀的屎即,就不要阻塞住技俐,回調出去统台。
作者:1115443231
鏈接:http://www.reibang.com/p/357ddad99de8
來源:簡書
著作權歸作者所有贱勃。商業(yè)轉載請聯(lián)系作者獲得授權,非商業(yè)轉載請注明出處仇穗。