objective-c文件操作的方法有哪些

ios开发中,ios开发是主要是用object-c语言,在使用 object-c编程语言 时,我们会对object-c中文件类进行各种各样的操作,那么应该如何对object c文件进行操作呢?下面就来看看object c文件操作方法:
常见的NSFileManger文件方法:
1.-(BOOL) contentsAtpath:path
从一个文件中读取数据
2.-(BOOL) createFileAtPath:path contents:(BOOL)data attributes:attr
向一个文件中写入数据
3.-(BOOL)removeFileAtPath:path handler;handler
删除一个文件
4.-(BOOL)movePath:from toPath:to handler:handler
重命名或者移动一个文件
5.-(BOOL)copyPath:from toPath:to handler:handler
比较这两个文件的内容
6.-(BOOL)fileExistsAtPath:path
测试文件是否存在
7.-(BOOL)isReadableFileAthPath:path
测试文件是否存在,并且是否能执行读操作
8.-(BOOL)isWritableFileAtPath:path
测试文件是否存在,并且是否能执行写操作
9.-(NSDictionary *)fileAttributesAtPath:path traverseLink:(BOOL)flag
获取文件的属性
10.-(BOOL)changeFileAttributes:attr atPath:path
更改文件属性

创建与删除:
//创建文件管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
//获取路径
//参数NSDocumentDirectory要获取那种路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//更改到待操作的目录下
[fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
//创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nilattributes文件的属性,初始为nil
[fileManager createFileAtPath:@"fileName" contents:nil attributes:nil];
//删除待删除的文件
[fileManager removeItemAtPath:@"createdNewFile" error:nil];
写入数据:
//获取文件路径
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"fileName"];

//待写入的数据
NSString *temp = @”Welcome to blog.iosxcode4.com”;
int data0 = 100000;
float data1 = 23.45f;
//创建数据缓冲
NSMutableData *writer = [[NSMutableData alloc] init];
//将字符串添加到缓冲中
[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
//将其他数据添加到缓冲中
[writer appendBytes:&data0 length:sizeof(data0)];
[writer appendBytes:&data1 length:sizeof(data1)];
//将缓冲的数据写入到文件中
[writer writeToFile:path atomically:YES];
[writer release];
读取数据:
int gData0;
float gData1;
NSString *gData2;
NSData *reader = [NSData dataWithContentsOfFile:path];
gData2 = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])]
encoding:NSUTF8StringEncoding];
[reader getBytes:&gData0 range:NSMakeRange([temp length], sizeof(gData0))];
[reader getBytes:&gData2 range:NSMakeRange([temp length] + sizeof(gData0), sizeof(gData1))];
NSLog(@”gData0:%@  gData1:%i gData2:%f”, gData0, gData1, gData2);
以上就是object-c文件操作方法汇总,此文仅限初学者,上面的操作方法都是小编从网上整理下来的,若有遗漏,欢迎大家补充。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值