iOS文件操作: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 Tips\nhttp://iPhoneDevelopTips,com";

//寫入文件

[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

//顯示文件目錄的內容

NSLog(@"Documentsdirectory:??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];

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\n", [fileSize unsignedLongLongValue]);

}

//文件創建日期

if (creationDate = [fileAttributes objectForKey:NSFileCreationDate]) {

NSLog(@"File creationDate:%@\n", creationDate);

//textField.text=NSFileCreationDate;

}

//文件所有者

if (fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName]) {

NSLog(@"Owner:%@\n", fileOwner);

}

//文件修改日期

if (fileModDate = [fileAttributes objectForKey:NSFileModificationDate]) {

NSLog(@"Modification date:%@\n", 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];

//獲取文件的創建日期

NSDate *modificationDate = (NSDate*)[fileAttributes objectForKey: NSFileModificationDate];

//獲取文件的字節大小

NSNumber *fileSize = (NSNumber*)[fileAttributes objectForKey: NSFileSize];

//格式化文件大小

nsstring A = [numberFormatter stringFromNumber: fileSize];

//格式化文件創建日期

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的文件操作方法的阻塞,而以流的方式進行操作則可以實現異步的讀取。

NSStream是可以異步工作的。可以注冊一個在流中有字節可讀的時候回調的函數,如果沒有可讀的,就不要阻塞住,回調出去。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 今天開始分析YYCache 包含的文件類 YYCache YYMemoryCache YYDiskCache YY...
    充滿活力的早晨閱讀 815評論 4 1
  • iOS開發-文件管理(一) 一、iOS中的沙盒機制 iOS應用程序只能對自己創建的文件系統讀取文件,這個獨立、封閉...
    MacShare閱讀 1,814評論 0 6
  • 一、iOS中的沙盒機制 iOS應用程序只能對自己創建的文件系統讀取文件,這個獨立、封閉、安全的空間,叫做沙盒。它一...
    1d5cb7cff98d閱讀 1,789評論 0 0
  • iOS的沙盒機制,應用只能訪問自己應用目錄下的文件。iOS不像Android,沒有SD卡概念,不能直接訪問圖像、視...
    ZorroZuo閱讀 1,608評論 0 0
  • 1、改變 UITextField 占位文字 顏色和去掉底部白框 [_userName setValue:[UICo...
    i_MT閱讀 1,065評論 0 2