Foundation 框架 NSFileManager,NSData 简单的文件操作

时间:2023-03-09 03:03:35
Foundation 框架 NSFileManager,NSData 简单的文件操作

一、简单展示NSFileManager的使用

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{ @autoreleasepool {
//创建文件管理对象
NSFileManager *fm = [NSFileManager defaultManager];
//要操作的文件名
NSString *fname = @"myfile";
//获取文件的字典
NSDictionary *attr;
//当前路径
NSString *path;
//获取当前路径
path = [fm currentDirectoryPath];
//NSLog(@"\nThe current path is : %@", path); //检测文件是否存在
if ([fm fileExistsAtPath: fname] == NO) {
//如果不存在则建立一个文件
[fm createFileAtPath: fname contents: NULL attributes:nil];
//NSLog(@"\nThe file is not exist!");
//return 0;
}
//拷贝创建一个新文件, 新文件若已存在则报错
if ([fm copyItemAtPath: fname toPath: @"newFile" error: NULL] == NO) {
NSLog(@"\n Can't copy the file");
return ;
}
//检测两个文件内容是否相同
if ([fm contentsEqualAtPath: fname andPath: @"newFile"] == NO) {
NSLog(@"\nThe contents is not same");
return ;
}
//移动或者改名文件
if ([fm moveItemAtPath: @"newFile" toPath: @"myFile2" error:NULL] == NO) {
NSLog(@"\nCan't change the name");
return ;
}
//获取文件数据字典
if ((attr = [fm attributesOfItemAtPath: fname error:NULL]) == nil) {
NSLog(@"\nGet attributets failed");
return ;
}
//文件大小
NSLog(@"%@", attr[NSFileSize]);
//文件类型
NSLog(@"%@", attr[NSFileType]);
//创建者
NSLog(@"%@", attr[NSFileOwnerAccountName]);
//
NSLog(@"%@", attr[NSFileCreationDate]);
//显示文件内容
NSLog(@"\n Show the file contents");
NSLog(@"\n%@", [NSString stringWithContentsOfFile: fname encoding:NSUTF8StringEncoding error:NULL]);
}
return ;
}

二、通过NSData完成副本制作

 int main(int argc, const char * argv[])
{ @autoreleasepool {
//通过NSDate来完成文件副本制作
NSFileManager *fm = [NSFileManager defaultManager];
NSData *dt; dt = [fm contentsAtPath: @"myfile"]; if (dt == nil) {
NSLog(@"Read file failed....");
return ;
} //将缓冲区NSData中的内容复制到文件中
if ([fm createFileAtPath:@"myFavoriteFile" contents: dt attributes:nil] == NO) {
NSLog(@"Creat backups failed");
return ;
} //读出文件内容
NSLog(@"\n%@", [NSString stringWithContentsOfFile:@"myFavoriteFile" encoding: NSUTF8StringEncoding error:NULL]);
}
return ;
}

三、简单的目录操作

 #import <Foundation/Foundation.h>

 int main(int argc, const char * argv[])
{ @autoreleasepool {
NSString *newDir = @"newDir";
NSString *currentPath;
NSFileManager *fm = [NSFileManager defaultManager]; //获取当前路径
currentPath = [fm currentDirectoryPath];
NSLog(@"\nCurrentpath is : \n%@", currentPath); //在当前目录下新建一个目录
if ([fm createDirectoryAtPath:newDir withIntermediateDirectories:TRUE attributes:nil error:NULL] == NO) {
NSLog(@"\nCouldn't creat the directory...");
return ;
} //更改路径名
if ([fm moveItemAtPath: newDir toPath: @"changeDir" error:NULL] == NO) {
NSLog(@"\nChange directory name failed");
return ;
} //更改当前路径
if ([fm changeCurrentDirectoryPath:@"changeDir"] == NO) {
NSLog(@"\nChange current directory failed");
return ;
}
NSLog(@"\nAfter change current directory.....");
currentPath = [fm currentDirectoryPath];
NSLog(@"\nCurrentpath is : \n%@", currentPath);
}
return ;
}