对于NSFileManager,文件或目录是使用文件的路径名唯一标识的。每一个路径名都是一个NSString对象,它可以是相对路径名,也可以是完整路径名。
相对路径名是相对于当前目录的路径名。所以,文件名file.m意味着当前目录中的file.m。斜线字符用于隔开路径中的目录列表。
完整路径名,也称绝对路径名,以斜线“/”开头,斜线实际上就是一个目录,称为 根目录。
这个特殊字符(~)用作用户主目录的缩写。点“ . ”表示当前目录,两点“ .. ”表示父目录
下面是常见的NSFileManager文件方法:
下面是一些基本的文件操作的代码示例:
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- NSString *fName = @"testfile.txt";
- NSFileManager *fm ;
- NSDictionary * attr;
- //创建文件管理对象
- fm = [NSFileManager defaultManager];
- //判断文件是否存在
- if([fm fileExistsAtPath:fName] == NO)
- {
- NSLog(@"File doesn't exist!");
- return 1;
- }
- //将 testfile.txt 文件拷贝出一个新的文件 newfile.txt
- if([fm copyPath:fName toPath:@"newfile.txt" handler:nil] == NO)
- {
- NSLog(@"File copy failed!");
- return 2;
- }
- //判断两个文件内容是否相等
- if([fm contentsEqualAtPath:fName andPath:@"newfile.txt"] == NO)
- {
- NSLog(@"File are not equal!");
- return 3;
- }
- //将文件 newfile.txt 重命名为 newfile2.txt
- if([fm movePath:@"newfile.txt" toPath:@"newfile2.txt" handler:nil] == NO)
- {
- NSLog(@"File rename failed!");
- return 4;
- }
- //获取文件 newfile2.txt 的大小,并输出
- 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]);
- //移出原始文件testfile.txt
- if([fm removeFileAtPath:fName handler:nil] == NO)
- {
- NSLog(@"File removal failed!");
- return 6;
- }
- NSLog(@"All operations were successful!");
- //输出文件内容
- NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile2.txt" encoding:NSUTF8StringEncoding error:nil]);
- }
- return 0;
- }
#import <Foundation/Foundation.h>int main(int argc, const char * argv[])
{@autoreleasepool {NSString *fName = @"testfile.txt";NSFileManager *fm ;NSDictionary * attr;//创建文件管理对象fm = [NSFileManager defaultManager];//判断文件是否存在if([fm fileExistsAtPath:fName] == NO){NSLog(@"File doesn't exist!");return 1;}//将 testfile.txt 文件拷贝出一个新的文件 newfile.txtif([fm copyPath:fName toPath:@"newfile.txt" handler:nil] == NO){NSLog(@"File copy failed!");return 2;}//判断两个文件内容是否相等if([fm contentsEqualAtPath:fName andPath:@"newfile.txt"] == NO){NSLog(@"File are not equal!");return 3;}//将文件 newfile.txt 重命名为 newfile2.txtif([fm movePath:@"newfile.txt" toPath:@"newfile2.txt" handler:nil] == NO){NSLog(@"File rename failed!");return 4;}//获取文件 newfile2.txt 的大小,并输出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]);//移出原始文件testfile.txtif([fm removeFileAtPath:fName handler:nil] == NO){NSLog(@"File removal failed!");return 6;}NSLog(@"All operations were successful!");//输出文件内容NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile2.txt" encoding:NSUTF8StringEncoding error:nil]);}return 0;
}