• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

Objective C中文件类的各种操作方法

C# 水墨上仙 3007次浏览

Objective C中文件类的各种操作方法
转自:http://blog.csdn.net/newjerryj/article/details/6263134

&nbsp&nbsp&nbsp本文来讲述&nbsp文件类的各种操作方法,示例如下:

NSString  *fName=@"testfile.m";  
NSFileManager *fm=NULL;  
NSDictionary  *dict=NULL;  
  
fm=[NSFileManager defaultManager];  
  
if ([fm fileExistsAtPath:fName]==NO) {  
    NSLog(@"file not exist!");  
      
    return 1;  
}  
  
   if ([fm copyPath:fName toPath:@"newfile" handler:nil]==NO) {  
    NSLog(@"copy failed!");  
}  
  
if ([fm movePath:@"newfile" toPath:@"newfolder" handler:nil]==NO) {  
    NSLog(@"move failed");  
}  
  
if ((dict=[fm fileAttributesAtPath:@"newfolder" traverseLink:NO])==nil) {  
    NSLog(@"get file attributes failed");  
}  
  
NSLog(@"file size is %i bytes",[[dict objectForKey:NSFileSize] intValue]);  
  
  
if ([fm removeFileAtPath:@"newfolder" handler:nil]==YES) {  
    NSLog(@"remove successful!");  
}  
 

NSData类的使用方法

NSData  *fileData=NULL;  
  
  
fm=[NSFileManager defaultManager];  
  
fileData=[fm contentsAtPath:@"testfile.m"];  
  
if (fileData==nil) {  
    NSLog(@"read file failed!");  
}  
  
if ([fm createFileAtPath:@"file2" contents:fileData attributes:nil]==YES) {  
    NSLog(@"create file success!");  
}  
 
 

对路径的操作方法:

NSString  *fName=@"testDir";  
NSFileManager *fm=NULL;  
//NSDictionary  *dict=NULL;  
NSString  *path=NULL;  
  
  
fm=[NSFileManager defaultManager];  
  
path=[fm currentDirectoryPath];  
  
NSLog(@"currentDir is: %@",path);  
  
//create a new directory  
[fm createDirectoryAtPath:fName attributes:nil];  
  
//rename the directory  
[fm movePath:fName toPath:@"newDir" handler:nil];    
  
//change currentdirectory  
[fm changeCurrentDirectoryPath:@"newDir"];  
  
path=[fm currentDirectoryPath];  
  
NSLog(@"currentDir is: %@",path);  
 

枚举某个目录的所有内容:

[cpp] view plaincopy
NSFileManager  *fm=NULL;  
NSDirectoryEnumerator *dirEnum=NULL;  
NSArray    *dirArray=NULL;  
NSString   *path=NULL;  
  
  
fm=[NSFileManager  defaultManager];  
  
path=[fm currentDirectoryPath];  
  
dirEnum=[fm enumeratorAtPath:path];  
  
while ((path=[dirEnum nextObject])!=nil) {  
    dirArray=[fm directoryContentsAtPath:[fm currentDirectoryPath]];  
}  
  
NSLog(@"%@",dirArray);  
 

NSFileHandle的使用示例:

NSFileHandle  *inFile, *outFile;  
NSData   *buffer;  
  
  
inFile=[NSFileHandle fileHandleForReadingAtPath:@"testfile.m"];  
  
[[NSFileManager defaultManager]createFileAtPath:@"newfile1" contents:nil attributes:nil];  
  
outFile=[NSFileHandle fileHandleForWritingAtPath:@"newfile1"];  
  
[outFile truncateFileAtOffset:0];  
  
buffer=[inFile readDataToEndOfFile];  
  
[outFile writeData:buffer];  
  
[inFile closeFile];  
[outFile closeFile];  


喜欢 (0)
加载中……