NSFileManager和NSFileHandle

来源:互联网 发布:苹果mac版cad看图软件 编辑:程序博客网 时间:2024/06/05 02:00
//file
文件操作
NSFileManager 
常见的NSFileManager文件的方法:
-(BOOL)contentsAtPath:path                从文件中读取数据
-(BOOL)createFileAtPath:path contents:(BOOL)data attributes:attr      向一个文件写入数据
-(BOOL)removeFileAtPath: path handler: handler   删除一个文件
-(BOOL)movePath: from toPath: to handler: handler 重命名或移动一个文件(to可能已经存在)
-(BOOL)copyPath:from toPath:to handler: handler 复制文件 (to不能存在) 
-(BOOL)contentsEqualAtPath:path1 andPath:path2    比较两个文件的内容 
-(BOOL)fileExistsAtPath:path    测试文件是否存在 
-(BOOL)isReadablefileAtPath:path 测试文件是否存在,且是否能执行读操作 
-(BOOL)isWritablefileAtPath:path 测试文件是否存在,且是否能执行写操作 
-(NSDictionary *)fileAttributesAtPath:path traverseLink:(BOOL)flag   获取文件的属性 
-(BOOL)changeFileAttributes:attr atPath:path                        更改文件的属性 
 
NSFileManager对象的创建 :
    NSFileManager *fm;
    fm = [NSFileManager defaultManager]; 
NSDictionary *attr =[fm fileAttributesAtPath: fname traverseLink: NO] ; //文件属性
             NSLog(@"file size is:%i bytes ",[[attr objectForKey:NSFileSize] intValue]);
NSData *data =[fm contentsAtPath:@"filename"];//文件内容
 
 
常见的NSFileManager目录的方法:
-(NSString *)currentDirectoryPath                      获取当前目录 
-(BOOL)changeCurrentDirectoryPath:path                更改当前目录 
-(BOOL)copyPath:from toPath:to handler:handler      复制目录结构,to不能已经存在 
-(BOOL)createDirectoryAtPath:path attributes:attr    创建目录 
-(BOOL)fileExistsAtPath:path isDirectory:(BOOL *)flag       测试文件是否为目录 (flag存储结构yes/no) 
-(NSArray *)contentsOfDirectoryAtPath:path              列出目录的内容 
-(NSDirectoryEnumerator *)enumeratorAtPath:path  枚举目录的内容 
-(BOOL)removeFileAtPath:path handler:handler    删除空目录 
-(BOOL)movePath:from toPath:to handler:handler    重命名或移动一个目录,to不能是已经存在的 
 
path= [fm currentDirectoryPath] ;
NSArray *dirarray;
NSDirectoryEnumerator *direnu;
 
direnu = [fm enumeratorAtPath:path];
NSLog(@"contents of %@\n",path);
BOOL flag;
while((path = [direnu nextObject])!=nil)
{
            NSLog(@"%@ ",path);
            [fm fileExistsAtPath:path isDirectory:&flag];
            if(flag == YES)
            [direnu skipDescendents]; //跳过子目录 
}
path= [fm currentDirectoryPath] ;
dirarray = [fm contentsOfDirectoryAtPath:path];
NSLog(@"%@ ",dirarray);
 
常用路径工具函数
NSString * NSUserName(); 返回当前用户的登录名 
NSString * NSFullUserName(); 返回当前用户的完整用户名 
NSString * NSHomeDirectory(); 返回当前用户主目录的路径 
NSString * NSHomeDirectoryForUser(); 返回用户user的主目录 
NSString * NSTemporaryDirectory(); 返回可用于创建临时文件的路径目录 
 
常用路径工具方法
-(NSString *) pathWithComponents:components                         根据components中元素构造有效路径 
-(NSArray *)pathComponents                                          析构路径,获取路径的各个部分 
-(NSString *)lastPathComponent                                       提取路径的最后一个组成部分 
-(NSString *)pathExtension                                           路径扩展名 
-(NSString *)stringByAppendingPathComponent:path                    将path添加到现有路径末尾 
-(NSString *)stringByAppendingPathExtension:ext                     将拓展名添加的路径最后一个组成部分 
-(NSString *)stringByDeletingPathComponent                           删除路径的最后一个部分 
-(NSString *)stringByDeletingPathExtension                           删除路径的最后一个部分 的扩展名 
-(NSString *)stringByExpandingTildeInPath                            将路径中的代字符扩展成用户主目录(~)或指定用户主目录(~user) 
-(NSString *)stringByResolvingSymlinksInPath                         尝试解析路径中的符号链接 
-(NSString *)stringByStandardizingPath                               通过尝试解析~、..、.、和符号链接来标准化路径 
使用路径NSPathUtilities.h 
tempdir = NSTemporaryDirectory(); 临时文件的目录名 
path = [fm currentDirectoryPath];
[path lastPathComponent]; 从路径中提取最后一个文件名 
fullpath = [path stringByAppendingPathComponent:fname];将文件名附加到路劲的末尾 
extenson = [fullpath pathExtension]; 路径名的文件扩展名 
homedir = NSHomeDirectory();用户的主目录 
component = [homedir pathComponents];  路径的每个部分 
 
NSProcessInfo类:允许你设置或检索正在运行的应用程序的各种类型信息
(NSProcessInfo *)processInfo                                  返回当前进程的信息
-(NSArray*)arguments                                           以NSString对象数字的形式返回当前进程的参数
-(NSDictionary *)environment                                   返回变量/值对词典。描述当前的环境变量
-(int)processIdentity                                          返回进程标识
-(NSString *)processName                                       返回进程名称
-(NSString *)globallyUniqueString                              每次调用该方法都会返回不同的单值字符串,可以用这个字符串生成单值临时文件名   
-(NSString *)hostname                                          返回主机系统的名称 
-(unsigned int)operatingSystem                                 返回表示操作系统的数字 
-(NSString *)operatingSystemName                                     返回操作系统名称 
-(NSString *)operatingSystemVersionString                                     返回操作系统当前版本
-(void)setProcessName:(NSString *)name                                将当前进程名称设置为name 
过滤数组中的文件类型  : [fileList pathsMatchingExtensions:[NSArrayarrayWithObject:@"jpg"]];
///////////////////////////////////////////////////////////////////////////////////////////////////////////
基本文件操作NSFileHandle
常用NSFileHandle方法
(NSFileHandle *)fileHandleForReadingAtPath:path                        打开一个文件准备读取
(NSFileHandle *)fileHandleForWritingAtPath:path                        打开一个文件准备写入
(NSFileHandle *)fileHandleForUpdatingAtPath:path                        打开一个文件准备更新(读取和写入)
-(NSData *)availableData                                                  从设备或通道返回可用数据
-(NSData *)readDataToEndOfFile                                            读取其余的数据直到文件末尾(最多UINT_MAX字节)
-(NSData *)readDataOfLength:(unsigned int)bytes 从文件读取指定数目bytes的内容
-(void)writeData:data                  将data写入文件
-(unsigned long long) offsetInFile      获取当前文件的偏移量
-(void)seekToFileOffset:offset         设置当前文件的偏移量 
-(unsigned long long) seekToEndOfFile      将当前文件的偏移量定位的文件末尾
-(void)truncateFileAtOffset:offset        将文件的长度设置为offset字节
-(void)closeFile                           关闭文件
 

获取文件大小 

 
Using the C FILE type:

int getFileSizeFromPath(char * path)
{
     FILE * file;
     int fileSizeBytes = 0;
     file = fopen(path,"r");
     if(file>0){
         fseek(file, 0, SEEK_END);
         fileSizeBytes = ftell(file);
         fseek(file, 0, SEEK_SET);
         fclose(file);
     }
     return fileSizeBytes;
}

or in XCode use the NSFileManager:

NSFileManager * filemanager = [[NSFileManager alloc]init];
if([filemanager fileExistsAtPath:[self getCompletePath] isDirectory:&isDirectory]){

     NSDictionary * attributes = [filemanager attributesOfItemAtPath:[self getCompletePath] error:nil];

// file size
     NSNumber *theFileSize;
     if (theFileSize = [attributes objectForKey:NSFileSize])

       _fileSize= [theFileSize intValue];
}

 1、文件的创建

 

-(IBAction) CreateFile

{

//对于错误信息

NSError *error;

// 创建文件管理器

NSFileManager *fileMgr = [NSFileManager defaultManager];

//指向文件目录

NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];


//创建一个目录

[[NSFileManager defaultManager]   createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] attributes:nil];


// File we want to create in the documents directory我们想要创建的文件将会出现在文件目录中

// Result is: /Documents/file1.txt结果为:/Documents/file1.txt

NSString *filePath= [documentsDirectory

stringByAppendingPathComponent:@"file2.txt"];

//需要写入的字符串

NSString *str= @"iPhoneDeveloper Tips\nhttp://iPhoneDevelopTips,com";

//写入文件

[str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

//显示文件目录的内容

NSLog(@"Documentsdirectory:  contentsOfDirectoryAtPath:documentsDirectory error:&error]);


}

 


 

 

2、对文件重命名

 

对一个文件重命名
想要重命名一个文件,我们需要把文件移到一个新的路径下。下面的代码创建了我们所期望的目标文件的路径,然后请求移动文件以及在移动之后显示文件目录。
//通过移动该文件对文件重命名
NSString *filePath2= [documentsDirectory
stringByAppendingPathComponent:@"file2.txt"];
//判断是否移动
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
NSLog(@"Unable to move file: %@", [error localizedDescription]);
//显示文件目录的内容
NSLog(@"Documentsdirectory: %@",
[fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);

 

 

3、删除一个文件

 


为了使这个技巧完整,让我们再一起看下如何删除一个文件:
//在filePath2中判断是否删除这个文件
if ([fileMgr removeItemAtPath:filePath2 error:&error] != YES)
NSLog(@"Unable to delete file: %@", [error localizedDescription]);
//显示文件目录的内容
NSLog(@"Documentsdirectory: %@",
[fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]);
一旦文件被删除了,正如你所预料的那样,文件目录就会被自动清空:

这些示例能教你的,仅仅只是文件处理上的一些皮毛。想要获得更全面、详细的讲解,你就需要掌握NSFileManager文件的知识。


 

 

4、删除目录下所有文件

 

//获取文件路径
- (NSString *)attchmentFolder{

NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *path = [document stringByAppendingPathComponent:@"Attchments"];


NSFileManager *manager = [NSFileManager defaultManager];


if(![manager contentsOfDirectoryAtPath:path error:nil]){

[manager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];

}


return path;

}

 

--清除附件
BOOL result = [[NSFileManager defaultManager] removeItemAtPath:[[MOPAppDelegate instance] attchmentFolder] error:nil];


 


IPhone中获取文件各项属性方法

-(NSData *)applicationDataFromFile:(NSString *)fileName
{
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *documentsDirectory =[paths objectAtIndex:0];
    NSString *appFile =[documentsDirectory stringByAppendingPathComponent:fileName];
    NSData *data =[[[NSData alloc]initWithContentsOfFile:appFile]autorelease];
    return data;
}


-(void)getFileAttributes
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *path = @"/1ct.rtf";
NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:path traverseLink:YES];
    NSLog(@"@@");
if (fileAttributes != nil) {
    NSNumber *fileSize;
    NSString *fileOwner, *creationDate;
    NSDate *fileModDate;
    //NSString *NSFileCreationDate

//文件大小
    if (fileSize = [fileAttributes objectForKey:NSFileSize]) {
        NSLog(@"File size: %qi\n", [fileSize unsignedLongLongValue]);
    }

//文件创建日期
    if (creationDate = [fileAttributes objectForKey:NSFileCreationDate]) {
        NSLog(@"File creationDate: %@\n", creationDate);
        //textField.text=NSFileCreationDate;
    }

//文件所有者
    if (fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName]) {
        NSLog(@"Owner: %@\n", fileOwner);
    }

//文件修改日期
    if (fileModDate = [fileAttributes objectForKey:NSFileModificationDate]) {
        NSLog(@"Modification date: %@\n", fileModDate);
    }
 }
else {
    NSLog(@"Path (%@) is invalid.", path);
   }
}

 

 

///////////////////

文件类型,文件缩略图呢???

 

============================

//获取当前应用程序的主目录
NSString directoryPath =NSHomeDirectory();


//获取当前目录下的所有文件
NSArray directoryContents = [[NSFileManager defaultManager] directoryContentsAtPath: directoryPath];

 

//获取一个文件或文件夹
NSString *selectedFile = (NSString*)[directoryContents objectAtIndex: indexPath.row];


//拼成一个完整路径
[directoryPath stringByAppendingPathComponent: selectedFile];

 

 


BOOL isDir;

//判断是否是为目录


if ([[NSFileManager defaultManager] fileExistsAtPath:selectedPath isDirectory:&isDir] && isDir)

{//目录
}

else

{//文件
}

 

 

 

 

//日期格式化
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

[dateFormatter setTimeStyle:NSDateFormatterNoStyle];


//数字格式化

NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];

[numberFormatter setPositiveFormat: @"#,##0.## bytes"];

 

 

//获取文件属性

NSDictionary *fileAttributes =[[NSFileManager defaultManager] fileAttributesAtPath: directoryPath traverseLink: YES];

//获取文件的创建日期

NSDate *modificationDate = (NSDate*)[fileAttributes objectForKey: NSFileModificationDate];

//获取文件的字节大小

NSNumber *fileSize = (NSNumber*)[fileAttributes objectForKey: NSFileSize];
//格式化文件大小
nsstring A = [numberFormatter stringFromNumber: fileSize];

//格式化文件创建日期

NSstring B =[dateFormatter stringFromDate: modificationDate];

 


[numberFormatter release];

[dateFormatter release];

 

//读取文件内容操作- (void) loadFileContentsIntoTextView{

 

 

//通过流打开一个文件

 

NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath: filePath];

 

[inputStream open];

 


NSInteger maxLength = 128;

uint8_t readBuffer [maxLength];

//是否已经到结尾标识

BOOL endOfStreamReached = NO;

// NOTE: this tight loop will block until stream ends

while (! endOfStreamReached)

{

NSInteger bytesRead = [inputStream read: readBuffer maxLength:maxLength];

if (bytesRead == 0)

{//文件读取到最后

endOfStreamReached = YES;

}

else if (bytesRead == -1)

{//文件读取错误

endOfStreamReached = YES;

}

else

{

NSString *readBufferString =[[NSString alloc] initWithBytesNoCopy: readBuffer length: bytesRead encoding: NSUTF8StringEncoding freeWhenDone: NO];   

//将字符不段的加载到视图

[self appendTextToView: readBufferString];

[readBufferString release];

}

}

[inputStream close];

[inputStream release];

}

 

 

 

 

异步文件读取  在网络方面,网络的不可靠性可能会造成上面方法的阻塞

 

nsstream是可以异步工作的。可以注册一个在流中有字节可读的时候回调的函数,如果没有可读的,就不要阻塞住

 
 
 
 
 
 
 
 
原创粉丝点击