objective-c 使用文件(一)

精贴 置顶
2226 0

Foundation 框架请允许你利用文件系统对文件或目录执行基本操作。这些基本操作是由NSFileManager类提供的,这个类的方法具有如下功能:

   * 创建 一个新文件
   * 从现有文件中读取数据
   * 将数据写入文件中
   * 重新命名文件
   * 删除文件
   * 测试文件是否存在
   * 确定文件的大小及其他属性
   * 复制文件
   * 测试两个文件的内容是否相同
上述多数据操作也可以直接对目录进行。例如,可以创建目录,读取其中的内容,或者删除目录。

管理文件和目录

每个文件方法都是对NSFileManager对象的调用,而NSFileManager对象 是通过向类发送一条defaultManager消息创建的,
如下所示:
NSFileManager *fm
...
fm = [NSFileManager defaultManager];
例如,要从当前目录删除名为todolist的文件,首先要创建一个NSFileManager对象(如前面所示),然后调用removeFileAtPath方法,
代码如下:
[fm removeFileAtPath: @"todolist" handler:nil];
可以测试返回结果,以确保文件删除:
if([fm removeFileAtPath:@"todolist" handler:nil] == NO)
{
    NSLog(@"Couldn't remove file todolist");
    return 1;
}
下面是一个基本文件操作的例子:
[cpp] view plaincopy


  //Basic ifle operations  
  //Assumes the existence of a file called "testfile"  
  //in ther current working directory  
  #import   
  #import   
  #import   
  #import   
  #import   
    
  int main(int argc, const char *argv[])  
  {  
      NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
      NSString *fName = @"testfile.txt";  
      NSFileManager *fm;  
      NSDictionary *attr;  
    
      //Need to create an instance of the file manager  
      fm = [NSFileManager defaultManager];  
    
      //Let's make sure our test file exists first  
      if([fm fileExistsAtPath: fName] == NO)  
      {  
          NSLog(@"File doesn't exist'");  
          return 1;  
      }  
    
      //Now let's make a copy  
    
      if([fm copyPath: fName toPath: @"newfile.txt" handler:nil] == NO)  
      {  
          NSLog(@"File copy failed");  
          return 2;  
      }  
    
      //Let's test to see if the two files are identical  
      if([fm contentsEqualAtPath: fName andPath: @"newfile.txt"] == NO)  
      {  
          NSLog(@"Files are not equal!");  
          return 3;  
      }  
    
      //Now let's rename the copy  
    
      if([fm movePath: @"newfile.txt" toPath: @"newfile2.txt" handler:nil] == NO)  
      {  
          NSLog(@"File rename failed!");  
          return 4;  
      }  
    
      //Get the size of newfile2  
    
      if((attr = [fm fileAttributesAtPath: @"newfile2.txt" traverseLink:NO]) == nil)  
      {  
          NSLog(@"Couldn't get file attributes!");  
          return 5;  
      }  
    
      NSLog(@"File size is %i bytes",[[attr objectForKey: NSFileSize] intValue]);  
    
      //And finally, let's delete the original file  
      if([fm removeFileAtPath: fName handler:nil] == NO)  
      {  
          NSLog(@"File removal failed!");  
          return 6;  
      }  
    
      NSLog(@"All operations were successful!");  
    
      //Display the contents of the newly-created file  
    
      NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile2.txt" encoding:NSUTF8StringEncoding error:nil]);  
    
      [pool drain];  
      return 0;  
  }  
 

使用NSData类
使用文件时,需要频繁地将数据读入一个临时存储区,它通常称为缓冲区。当收集数据,以便随后将这些数据输出到文件中时,
通常也使用存储区。Foundation的NSData类提供了一种简单的方式,它用来设置缓冲 区、将文件的内容读入缓冲区,或将缓冲区的内容写到一个文件。
下面是一个使用NSData 的例子:

[cpp] view plaincopy


 #import   
#import   
#import   
#import   
#import   
   
//make a copy of file  
int main(int argc, const char *argv[])  
{  
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
     NSFileManager *fm;  
     NSData *fileData;  
   
   
     fm = [NSFileManager defaultManager];  
   
     //Read the file newfile2  
     fileData = [fm contentsAtPath: @"newfile2.txt"];  
   
     if(fileData == nil)  
     {  
         NSLog(@"File read failed!");  
         return 1;  
     }  
.   
     //Write the data to newfile3  
     if([fm createFileAtPath: @"newfile3.txt" contents: fileData attributes:nil] == NO)  
     {  
         NSLog(@"Couldn't create the copy!");  
         return 2;  
     }  
   
     NSLog(@"File copy was successful!");  
   
     [pool drain];  
     return 0;  
}  


使用目录
NSFileManager类中,还有很多操作目录的方法。
下面是一个例子:
[cpp] view plaincopy


 #import   
#import   
#import   
#import   
   
   
int main(int argc, const char *argv[])  
{  
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
     NSFileManager *fm;  
     NSString *dirName = @"testdir";  
     NSString *path;  
   
   
     fm = [NSFileManager defaultManager];  
   
     //Get current directory  获取当前目录
     path = [fm currentDirectoryPath];  
     NSLog(@"Current directory path is %@",path);  
   
     //Create a new directory  创建一个新目录
     if([fm createDirectoryAtPath: dirName attributes: nil] == NO)  
     {  
         NSLog(@"Couldn't create directory!");  
         return 1;  
     }  
   
     //Rename the new directory  重命名的新目录
     if([fm movePath: dirName toPath: @"newdir" handler: nil] == NO)  
     {  
         NSLog(@"Directory rename failed!");  
         return 2;  
     }  
   
     //Change directory into the new directory  改变目录到新的目录
     if([fm changeCurrentDirectoryPath: @"newdir"] == NO)  
     {  
         NSLog(@"Change directory failed!");  
         return 3;  
     }  
   
     //Now get and display current working directory  现在,并显示当前工作目录
     path = [fm currentDirectoryPath];  
     NSLog(@"Current directory path is %@ ",path);  
   
     NSLog(@"All operations were successful!");  
   
   
     [pool drain];  
     return 0;  
}  

枚举目录中的内容
directoryContentsAtPath 列出目录内容
enumeratorAtPath
  有时需要枚举目录里的内容,就需要用到enumeratorAtPath:方法或者directoryContentsAtPath: 方法,来完成枚举过程。
如果使用第一种方法,一次可以枚举指定目录中的每个文件,默认情况下,如果其中一个文件为目录,那么也会递归枚举它的内容。
在这个过程中,通过向枚举对象发送一条skipDescendants消息,可以动态的地阻止递归过程,从而不再枚举目录中的内容。
   对于directoryContentsAtPath:方法,使用这个方法,可心枚举指定目录的内容,并在一个数组中返回文件列表。
如果这个目录中的任何文件本身是个目录,这个方法并不递归枚举它的内容。
下面一个例子是这两个方法的使用:

[cpp] view plaincopy


 #import   
#import   
#import   
#import   
   
//enumeratorAtPath:方法和directoryContentsAtPath:方法  
//的区别是:前者遍历子目录,后者不遍历子目录  
int main(int argc, const char *argv[])  
{  
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];  
     NSFileManager *fm;  
     NSString *path;  
     NSDirectoryEnumerator *dirEnum;  
     NSArray *dirArray;  
   
   
     fm = [NSFileManager defaultManager];  
   
     //Get current directory path  
     path = [fm currentDirectoryPath];  
   
     //Enumerate the directory  
   
     dirEnum = [fm enumeratorAtPath:path];  
   
     NSLog(@"Contents of %@: ",path);  
     while((path = [dirEnum nextObject]) != nil)  
     NSLog(@"%@",path);  
   
     //Another way to enumerate a directory  
     dirArray = [fm directoryContentsAtPath:[fm currentDirectoryPath]];  
     NSLog(@"Contents using directoryContentsAtPath:");  
   
     for(int i = 0; i < [dirArray count];i++)  
     {  
        NSLog(@"%@",[dirArray objectAtIndex: i]);  
     }  
   
     [pool drain];  
     return 0;  
}  

  • 没有任何评论
今日天气 ···

···

···

···

热门排行
CSS cursor鼠标样式一览表 2012-06-25
.NET后台写JS代码 2011-11-03
网站地址多出jdfwkey的问题解析及... 2010-08-25
数据库xxx的日志已满,请备份该数... 2013-07-19
百度、google、Yahoo网站地图制作... 2011-01-30
<a>标签的伪类书写顺序问题... 2010-09-04
什么是长尾关键词? 2010-09-24
CEO名言 2010-08-31
Mysql 主从数据库同步 2010-09-12
用ASP实现网页BBS 2010-11-01
博主推荐
本个人博客微信公众平台上线啦~~... 2013-10-13
饼哥网络互联上线啦~~要买域名空... 2013-09-20
网站title标题如何正确修改不会被... 2013-08-26
饼哥通讯录系统上线啦,欢迎大家... 2013-08-24
ASP .NET MYSQL 的简单分页 并不... 2013-08-19
网站有弹窗广告这样的站点,百度... 2013-08-17
做淘宝SEO优化需要注意的8大问题 2013-08-17
淘宝网怎么做SEO优化 2013-08-17
站长们要学习的“苍井空精神” 2013-08-17
苹果公司今日发布了iOS 7第五个开... 2013-08-07
随便看看
饼哥淘宝客网站-淘趣购上线啦 2013-09-20
ASP中使用Session变量的优缺点 2010-10-25
win7系统如何设置虚拟内存 2013-07-29
Java基础:创建成员内部类的注意... 2013-06-26
Baiduspider - 百度蜘蛛 2010-10-02
php计算脚本执行时间 2010-10-10
.net2.0邮件发送代码 2010-09-11
URL标准化是什么意思? 2010-09-23
什么是长尾关键词? 2010-09-24
获取Android系统的唯一识别码 2013-06-27
RSS新闻
传媒新闻
CSDN
八卦新闻
女性新闻
台湾新闻
互联网
军事-新浪博客
IT-新浪博客
汽车新闻
游戏新闻
国际新闻
国内新闻
体育新闻
我的微博
北京 上海 杭州 深圳 广州 成都