---恢复内容开始---
首先,管理文件的一些方法,这里主要用到的是NSFileManager类,也用到了一些NSData类,NSData类创建的对象相当于是文件的缓存。
int main(int argc, const char * argv[]) { @autoreleasepool { NSString *fName = @"testfile"; NSFileManager *fm; NSDictionary *attr; NSData *fileData; //需要创建文件管理器的实例 fm = [NSFileManager defaultManager]; //首先确认测试文件存在 if ([fm fileExistsAtPath:fName] == NO) { NSLog(@"File doesn‘t exist!!"); return 1; } //创建一个副本 if ([fm copyItemAtPath:fName toPath:@"newfile" error:NULL] == NO) { NSLog(@"File Copy Failed!"); return 2; } //测试两个文件是否一致 if([fm contentsEqualAtPath:fName andPath:@"newfile"] == NO){ NSLog(@"Files are not Equal!"); return 3; } //重命名副本 if ([fm moveItemAtPath:@"newfile" toPath:@"newfile2" error:NULL] == NO) { NSLog(@"File rename Failed!"); return 4; } //获取newfile2的大小 if((attr = [fm attributesOfItemAtPath:@"newfile2" error:NULL]) == nil){ NSLog(@"Couldn‘t get file attributes!"); return 5; } NSLog(@"File size is %llu bytes",[[attr objectForKey:NSFileSize]unsignedLongLongValue]); //删除原始文件 if ([fm removeItemAtPath:fName error:NULL] == NO) { NSLog(@"file removal failed!"); return 6; } NSLog(@"All operations were successful"); //显示新创建的文件内容 NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile2" encoding:NSUTF8StringEncoding error:NULL]); //读取文件newfile2 fileData = [fm contentsAtPath:@"newfile2"]; if(fileData == nil){ NSLog(@"File read faild!!"); } //将缓存数据写入newfile3 if ([fm createFileAtPath:@"newfile3" contents:fileData attributes:nil] == NO) { NSLog(@"Couldn‘t create the copy!"); } NSLog(@"File copy was successful!"); } return 0; }
第二部分是关于文件目录的一些操作,比如说显示文件目录、显示目录下的文件等等:
int main(int argc, const char * argv[]) { @autoreleasepool { NSString *dirName = @"testdir"; NSString *path; NSFileManager *fm; NSDirectoryEnumerator *dirEnum; NSArray *dirArray; //创建文件管理器的实例 fm = [NSFileManager defaultManager]; //获取当前目录 path = [fm currentDirectoryPath]; NSLog(@"Current Directionary path is %@",path); //创建一个新的目录 if ([fm createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:NULL] == NO) { NSLog(@"Couldn‘t create directory!"); return 1; } //重新命名新的目录 if ([fm moveItemAtPath:dirName toPath:@"newdir" error:NULL] == NO) { NSLog(@"Directionary rename failed!"); return 2; } //更改目录到新的目录 if ([fm changeCurrentDirectoryPath:@"newdir"] == NO) { NSLog(@"Change Directionart failed!"); return 3; } //获取并显示当前的工作目录 path =[fm currentDirectoryPath]; NSLog(@"Current Directionary path is %@",path); //枚举目录 dirEnum = [fm enumeratorAtPath:path]; NSLog(@"Contents of %@",path); while ((path = [dirEnum nextObject]) != nil) { NSLog(@"%@",path); } //另一种枚举目录的方法 dirArray = [fm contentsOfDirectoryAtPath:[fm currentDirectoryPath] error:NULL]; NSLog(@"Contents using contentsOfDirectoryAtPath:error:"); for (path in dirArray) { NSLog(@"%@",path); } } return 0; }
时间: 2024-10-29 19:09:00