OC - 文件处理

OC - 文件处理 首页 / iOS入门教程 / OC - 文件处理

无法使用该应用程序直观地说明文件处理,因此下面介绍用于处理文件的关键方法。请注意,该应用程序捆绑包仅具有读取权限,无涯教程将无法修改文件。您仍然可以修改应用程序的documents目录。

访问和操作文件的方法将在下面讨论,在这里,无涯教程必须将FilePath1,FilePath2和FilePath字符串替换为所需的完整文件路径,以执行所需的操作。

链接:https://www.learnfk.comhttps://www.learnfk.com/ios/ios-file-handling.html

来源:LearnFk无涯教程网

文件是否存在

NSFileManager *fileManager = [NSFileManager defaultManager];

//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory NSUserDomainMask YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];

if ([fileManager fileExistsAtPath:@""]==YES) {
   NSLog(@"File exists");
}

比较文件内容

if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
   NSLog(@"Same content");
}

检查读写状态

if ([fileManager isWritableFileAtPath:@"FilePath"]) {
   NSLog(@"isWritable");
}

if ([fileManager isReadableFileAtPath:@"FilePath"]) {
   NSLog(@"isReadable");
}

if ( [fileManager isExecutableFileAtPath:@"FilePath"]) {
   NSLog(@"is Executable");
}

移动文件

if([fileManager moveItemAtPath:@"FilePath1" 
   toPath:@"FilePath2" error:NULL]) {
   NSLog(@"Moved successfully");
}

复制文件

if ([fileManager copyItemAtPath:@"FilePath1" 
   toPath:@"FilePath2"  error:NULL]) {
   NSLog(@"Copied successfully");
}

删除文件

if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
   NSLog(@"Removed successfully");
}

读取文件

NSData *data = [fileManager contentsAtPath:@"Path"];

写入文件

[fileManager createFileAtPath:@"" contents:data attributes:nil];

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

现代C++编程实战 -〔吴咏炜〕

小马哥讲Spring核心编程思想 -〔小马哥〕

分布式协议与算法实战 -〔韩健〕

小马哥讲Spring AOP编程思想 -〔小马哥〕

大数据经典论文解读 -〔徐文浩〕

Web漏洞挖掘实战 -〔王昊天〕

手把手教你落地DDD -〔钟敬〕

运维监控系统实战笔记 -〔秦晓辉〕

互联网人的数字化企业生存指南 -〔沈欣〕

好记忆不如烂笔头。留下您的足迹吧 :)