NSFileManager是Objective-C中管理文件的类。
#import
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSFileManager *fm=[NSFileManager defaultManager];
NSString *file1=@"/Users/fhp/Desktop/1.txt";
NSString *file2=@"/Users/fhp/Desktop/2.txt";
NSData *data=[fm contentsAtPath:file2];
//读取文件内容
if(![fm fileExistsAtPath:file1])
{
[fm createFileAtPath:file1 contents:data attributes:nil];
//如果文件不存在,就以file2的文件内容创建file1
}
NSLog(@"%@",[NSString stringWithContentsOfFile:file1 encoding:NSUTF8StringEncoding error:nil]);
//输出文件内容
[fm removeItemAtPath:file2 error:nil];
//删除文件file2
[fm movePath:file1 toPath:file2 handler:nil];
//移动file1到file2,因为在同一目录,所以只是简章的改名
//下面是目录枚举
NSDirectoryEnumerator *dir=[fm enumeratorAtPath:@"/Users/fhp/"];
NSString *path=[NSString new];
while ((path=[dir nextObject])!=nil) {
NSLog(@"%@",path);
}
//上面这种方法会递归
//下面这种不会
NSArray *array=[fm directoryContentsAtPath:@"/Users/fhp/"];
for(NSString *p in array)
NSLog(@"%@",p);
}
return 0;
}