文件或目录是使用文件的路径名唯一标识,每个路径名都是一个NSString对象。
路径名分为相对路径名和完整路径名:
相对路径名是相当于当前目录的路径名。以Student类为例,文件名Student.m意味着当前目录中的文件Student.m。
完整路径名也称绝对路径名,以斜线/开始,每个斜线实际上就是一个目录,第一个斜线就是根目录。
特殊字符(~):~computer表示用户computer的主目录的缩写,它可能是/User/computer。
常见NSFileManager文件方法:
复制文件:(to不能是已存在的)
- (BOOL)copyPath:(NSString *)srctoPath:(NSString *)dest handler:(id)handler
重命名或者移动一个文件:(to可能是已存在的)
- (BOOL)movePath:(NSString *)srctoPath:(NSString *)dest handler:(id)handler
删除一个文件:
- (BOOL)removeFileAtPath:(NSString*)path handler:(id)handler
测试文件是否存在:
- (BOOL)fileExistsAtPath:(NSString *)path;
测试文件是否存在,并且能否执行读操作
- (BOOL)isReadableFileAtPath:(NSString *)path;
测试文件是否存在,并且能否执行写操作
- (BOOL)isWritableFileAtPath:(NSString*)path;
从文件中读取数据:
- (NSData *)contentsAtPath:(NSString*)path;
向文件中写入数据:
- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;
获取文件属性:
-(NSDictionary*)
更改文件属性:
- (BOOL)changeFileAttributes:(NSDictionary*)attributes atPath:(NSString *)path
简单的创建,读文件例子:
#import<Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *fname=@"testfile.txt";
NSString *text=@"I am a student";
NSFileManager *fm;
NSData *data=[text dataUsingEncoding:NSUTF8StringEncoding];
fm=[NSFileManager defaultManager];
[[NSFileManager defaultManager]createFileAtPath:fname contents:nil attributes:nil]; //如果没有文件,创建一个是必须的
if ([fm fileExistsAtPath:fname]==NO) {
NSLog(@"文件没有生成");
exit(1);
}
BOOL isOk=[fm createFileAtPath:fname contents:data attributes:nil];
if (isOk) {
NSLog(@"文件创建成功");
}else{
NSLog(@"失败");
}
NSLog(@"%@",[NSString stringWithContentsOfFile:fname encoding:NSUTF8StringEncoding error:nil]);
}
return 0;
}