在Objective-C 中的 Foundation 框架中,文件操作是由NSFileManager 类来实现的。
下面通过例子来说明如何创建一个文件,并向文件中写内容,以及如何读出文件中的内容:
- (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);}
文件的一些常规操作,如复制文件、删除文件、移动文件等:
- (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"); }}