日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

[转载]IPhone之NSFileManager的使用

發布時間:2025/5/22 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [转载]IPhone之NSFileManager的使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文地址:IPhone之NSFileManager的使用作者:飛舞的雞毛

1、文件的創建

?

-(IBAction) CreateFile

{

//對于錯誤信息

NSError *error;

// 創建文件管理器

NSFileManager *fileMgr = [NSFileManager defaultManager];

//指向文件目錄

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


//創建一個目錄

[[NSFileManager defaultManager]?? createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] attributes:nil];


// File we want to create in the documents directory我們想要創建的文件將會出現在文件目錄中

// Result is: /Documents/file1.txt結果為:/Documents/file1.txt

NSString *filePath= [documentsDirectory

stringByAppendingPathComponent:@"file2.txt"];

//需要寫入的字符串

NSString *str= @"iPhoneDeveloper Tipsnhttp://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]);
//顯示文件目錄的內容
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];

轉載于:https://www.cnblogs.com/xiaonanxia/archive/2012/10/18/2729248.html

總結

以上是生活随笔為你收集整理的[转载]IPhone之NSFileManager的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。