objective-c 使用文件(一)

  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;

}

 

下面是一个基本文件操作的例子:

//Basic ifle operations //Assumes the existence of a file called "testfile" //in ther current working directory #import <Foundation/NSObject.h> #import <Foundation/NSString.h> #import <Foundation/NSFileManager.h> #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSDictionary.h> 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 的例子:

 

#import <Foundation/NSObject.h> #import <Foundation/NSString.h> #import <Foundation/NSFileManager.h> #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSData.h> //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类中,还有很多操作目录的方法。

下面是一个例子:

#import <Foundation/NSObject.h> #import <Foundation/NSString.h> #import <Foundation/NSFileManager.h> #import <Foundation/NSAutoreleasePool.h> 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; }

 

 

 

 

枚举目录中的内容

 

 

   有时需要枚举目录是的内容,就需要用到enumeratorAtPath:方法或者directoryContentsAtPath: 方法,来完成枚举过程。

如果使用第一种方法,一次可以枚举指定目录中的每个文件,默认情况下,如果其中一个文件为目录,那么也会递归枚举它的内容。

在这个过程中,通过向枚举对象发送一条skipDescendants消息,可以动态的地阻止递归过程,从而不再枚举目录中的内容。

   对于directoryContentsAtPath:方法,使用这个方法,可心枚举指定目录的内容,并在一个数组中返回文件列表。

如果这个目录中的任何文件本身是个目录,这个方法并不递归枚举它的内容。

 

下面一个例子是这两个方法的使用:

#import <Foundation/NSArray.h> #import <Foundation/NSString.h> #import <Foundation/NSFileManager.h> #import <Foundation/NSAutoreleasePool.h> //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; }

 

 

 

 

 

你可能感兴趣的:(manager,测试,File,Path,encoding,attributes)