设为首页 加入收藏

TOP

Objective-C文件的存取
2014-02-08 12:43:28 来源: 作者: 【 】 浏览:115
Tags:Objective-C 文件 存取

  一般的,文件存取都有两种方式,这两种方式主要是根据文件的内容来划分的。对于由文字组成的文件可以利用字符读写的方式,而其他类型的文件通常用字节码的形式来存的(当然,我们亦可以用字节码来存文字)。

  在OC中NSString类直接能够调用内部的方法去读区、写入string.而不像java得用IO流类进行一系列的封装。而且OC的文本访问是很简单的,比如用下面的几行就能对特定的文本文件写入:

  #pragma 使用NSString写入文件中:

  NSError *error = nil;

  NSMutableString *str = [[NSMutableString alloc] init];

  for(int i=0;i<10;i++){

  [str appendString:@"你好!hello\n"];

  }

  if([str writeToFile:@"/tmp/my.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error]){

  NSLog(@"success");

  }

  else{

  NSLog(@"error:%@",[error localizedDescription]);

  }

  而读取也是很少的:

  #pragma 使用NSString从文件中读取:

  NSError *error = nil;

  NSString *str = [[NSString alloc] initWithContentsOfFile:@"/tmp/my.txt" encoding:NSUTF8StringEncoding error:&error];

  if (str) {

  NSLog(@"content:%@",str);

  }

  else {

  NSLog(@"error:%@",[error localizedDescription]);

  }

  然后呢?

  当使用NSData的时候,我更加震惊地体会到了Objective-C的独特简便性,对于java/c/c++显然有挺大的优势,而对于python/php来说也是简单明确的。

  一下就是几行代码实现使用NSData的文件读写。

  #pragma 使用NSData存取

  NSError *error = nil;

  NSData *data = [[NSData alloc] initWithContentsOfFile:@"/tmp/my.txt"];

  if ([data writeToFile:@"/tmp/my2.txt" options:NSDataWritingAtomic error:&error]) {

  NSLog(@"success");

  }

  else{

  NSLog(@"error:%@",error);

  }

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言实现二叉树创建和查找 下一篇objective-c中实例变量的写法

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: