在Objective-C 中的 Foundation 框架中,文件操做是由NSFileManager 類來實現的。框架
下面經過例子來講明如何建立一個文件,並向文件中寫內容,以及如何讀出文件中的內容:spa
- (void)testFileCreate { NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; filePath = [filePath stringByAppendingPathComponent:@"new.txt"]; NSLog(@"filePath = %@",filePath); // 判斷文件是否存在 if (![fileManager fileExistsAtPath:filePath]){ // 若文件不存在,則新建文件 [fileManager createFileAtPath:filePath contents:nil attributes:nil]; } // 向文件中寫內容,經過文件句柄,NSFileHandle實現 NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; NSString *content = @"hey,brother.This is a test."; NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding]; [fileHandle writeData:contentData]; // 關閉文件 [fileHandle closeFile]; // 讀取文件中的內容 fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; NSData *readData = [fileHandle readDataToEndOfFile]; // data 轉 NSString NSString *readStr = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding]; NSLog(@"readStr = %@",readStr); [fileHandle closeFile]; // 直接以NSString 的方式讀取文件 NSString *contentStr = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; NSLog(@"contentStr = %@",contentStr); }
文件的一些常規操做,如複製文件、刪除文件、移動文件等:code
- (void)testFileOperation { // 得到臨時目錄 NSString *tempPath = NSTemporaryDirectory(); NSLog(@"tempPath = %@",tempPath); // 最後一級目錄 NSLog(@"last = %@", [tempPath lastPathComponent] ); // 在最後增長一級目錄,原目錄不變,返回一個新的目錄字符串 NSLog(@"add last = %@",[tempPath stringByAppendingPathComponent:@"add"]); // 刪除最後一級目錄,原目錄不變,返回一個新的目錄字符串 NSLog(@"del last = %@",[tempPath stringByDeletingLastPathComponent]); NSString *filePath = [tempPath stringByAppendingPathComponent:@"test.txt"]; NSLog(@"filePath = %@",filePath); // 擴展名,輸出爲 txt NSLog(@"extension = %@",[filePath pathExtension]); NSFileManager *manager = [NSFileManager defaultManager]; if(![manager fileExistsAtPath:filePath]){ [manager createFileAtPath:filePath contents:nil attributes:nil]; } NSString *newPath = [tempPath stringByAppendingPathComponent:@"newtest.txt"]; // 拷貝文件 [manager copyItemAtPath:filePath toPath:newPath error:nil]; if([manager fileExistsAtPath:newPath]){ NSLog(@"copy success"); } // 刪除文件 [manager removeItemAtPath:newPath error:nil]; if(![manager fileExistsAtPath:newPath]){ NSLog(@"remove success"); } // 文件是否可讀 if([manager isReadableFileAtPath:filePath]){ NSLog(@"readable"); } // 文件是否可寫 if([manager isWritableFileAtPath:filePath]){ NSLog(@"writeable"); } }