IOS中NSFileManager的操作 [Z]

來源:互聯網
上載者:User

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];

}

 

 

 

 

非同步檔案讀取  在網路方面,網路的不可靠性可能會造成上面方法的阻塞


nsstream是可以非同步工作的。可以註冊一個在流中有位元組可讀的時候回調的函數,如果沒有可讀的,就不要阻塞住

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.