OC-文件操作
一.归档NSKeyedArchiver==========================
1.第一种方式:存储一种数据。=====================
//归档
//第一种写法
//对象--文件
NSArray* array = [[NSArray alloc]initWithObjects:@"zhang",@"wang",@"li", nil];
NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.txt"];
BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];
if (success) {
NSLog(@"保存成功");
}
//解归档
NSArray* arr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@",arr);
2.第二种方式:存储并行数据(存储多种数据)。====================================
//第二种写法:
NSArray* array = @[@"one",@"two",@"three"];
NSDictionary* dic = @{@"key":@"value"};
NSString* str = @"我是中国人,我爱中国";
//NSData 数据流类
//用来存储复杂的数据,把复杂的数据转成数据流格式,可以方便进行存储和传输。
//例如:图片、大文件
//断点续传,假如图片有20M大,
//发邮件:添加附件
NSMutableData* data = [[NSMutableData alloc]init];
//initForWritingWithMutableData 指定要写入的数据流文件
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
//编码数据,参数一:要准备编码的数据;参数二:编码数据的key,key随便写
[archiver encodeObject:array forKey:@"array"];
[archiver encodeObject:dic forKey:@"dic"];
[archiver encodeObject:str forKey:@"str"];
//编码完成
[archiver finishEncoding];
//指定文件路径
NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"file2"];
//写入文件
[data writeToFile:filePath atomically:YES];
//====================************************************=========================//
//先把路径下的文件读入数据流中
NSMutableData* fileData = [[NSMutableData alloc]initWithContentsOfFile:filePath];
//把数据流文件读入到了 解归档中
NSKeyedUnarchiver* unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:fileData];
//进行解归档
NSArray* UnArray = [unArchiver decodeObjectForKey:@"array"];
NSDictionary* UnDic = [unArchiver decodeObjectForKey:@"dic"];
NSString* UnStr = [unArchiver decodeObjectForKey:@"str"];
//打印
NSLog(@"%@\n%@\n%@\n",UnArray,UnDic,UnStr);
三.第三种归档方式:对类对象进行归档=======================================
1.先在类的头文件中实现<NSCoding>协议
2.在.m中重新编码和解码协议。
//重新initWithCoder 解码方法
-(id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"我是解码方法,我负责解码");
self = [super init];
if (self) {
_name = [aDecoder decodeObjectForKey:@"name"];
_phone = [aDecoder decodeObjectForKey:@"phone"];
_address = [aDecoder decodeObjectForKey:@"address"];
}
return self;
}
//重新编码方法
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeObject:_phone forKey:@"phone"];
[aCoder encodeObject:_address forKey:@"address"];
}
//【注】forKey:是字符串;编码方法和解码方法字符串要一致
四.NSFileManager 文件管理类===============================================
1.文件路径------------------------------------------------------------------------------
//根路径
NSString* homePath = NSHomeDirectory();
NSLog(@"%@",homePath);
//oc中有三个目录是可以操作的。
/*
1.Documents//文稿目录
2.tmp//临时目录:程序退出的时候,临时目录内容可能会被情况
3.library--->Cache//缓存目录//app目录下
*/
//获取Documents 目录
//写法一
NSString* Documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSLog(@"Documents :%@",Documents);
//写法二
NSString* Documents1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES) objectAtIndex:0];
NSLog(@"Documents : %@",Documents1);
//获取应用程序的主目录
NSString* userName = NSUserName();
NSString* rootPath = NSHomeDirectoryForUser(userName);
NSLog(@"app root path:%@",rootPath);
//获取cache目录
NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"cache :%@",cachePath);
//获取tmp目录
NSString* tmpPath = NSTemporaryDirectory();
NSLog(@"tmp:%@",tmpPath);
2.创建目录和文件------------------------------------------------------------------------------------
//获取根目录
NSString* homePath = NSHomeDirectory();
//创建了一个文件管理器
NSFileManager* fileMgr = [NSFileManager defaultManager];
//拼接出想要创建的文件路径
NSString* filePath = [NSString stringWithFormat:@"%@/myFolder",homePath];
//创建文件目录
//第一个参数传入想要创建的文件目录,第二个参数指导是否创建不存在的文件夹,yes代表创建
BOOL isOk = [fileMgr createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
if (isOk) {
NSLog(@"创建文件目录成功");
}
NSString* string = @"我爱记歌词";
//把内容写入到指定路径下的指定文件中
BOOL isWriteOk = [string writeToFile:[NSString stringWithFormat:@"%@/1.txt",filePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (isWriteOk) {
NSLog(@"写入文件成功");
}
//数组保存
NSArray* array = @[@"我是一",@"我是三",@"我是周7"];
BOOL isWriteOK1 = [array writeToFile:[NSString stringWithFormat:@"%@/2.txt",filePath] atomically:YES];
if (isWriteOK1) {
NSLog(@"数组写入文件成功");
}
//字典保存
NSDictionary* dic = @{@"key":@"value"};
BOOL isWriteOK2 = [dic writeToFile:[NSString stringWithFormat:@"%@/3.txt",filePath] atomically:YES];
if (isWriteOK2) {
NSLog(@"字典写入文件成功");
}
3.对文件进行重命名---------------------------------------------------------------------------------------------
//获取根目录
NSString* homePath = NSHomeDirectory();
//创建了一个文件管理器
NSFileManager* fileMgr = [NSFileManager defaultManager];
//拼接出想要创建的文件路径
NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/1.txt",homePath];
[fileMgr moveItemAtPath:filePath toPath:[NSString stringWithFormat:@"%@/ai.txt",homePath] error:nil];
4.删除一个文件---------------------------------------------------------------------------------------------
//声明了一个错误信息的对象
NSError* error;
//获取根目录
NSString* homePath = NSHomeDirectory();
//创建了一个文件管理器
NSFileManager* fileMgr = [NSFileManager defaultManager];
//拼接出想要创建的文件路径
NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];
//删除文件
//如果方法执行返回是NO,error会保存错误信息,如果方法执行返回是YES,error = nil
BOOL isok = [fileMgr removeItemAtPath:filePath error:&error];
if (isok) {
NSLog(@"删除文件成功");
}
else
{
NSLog(@"删除文件失败");
//打印错误信息
NSLog(@"%@",error.localizedDescription);
}
Δ【扩展】NSError类,是一个错误信息类
//删除文件
//如果方法执行返回是NO,error会保存错误信息,如果方法执行返回是YES,error = nil
BOOL isok = [fileMgr removeItemAtPath:filePath error:&error];
∆5.删除目录下的所有文件---------------------------------------------------------------------------------------------
//获取根目录
NSString* homePath = NSHomeDirectory();
//创建了一个文件管理器
NSFileManager* fileMgr = [NSFileManager defaultManager];
//拼接出想要创建的文件路径
// NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];
//如果删除的目录中不带具体的文件,则删除的是整个目录
[fileMgr removeItemAtPath:[NSString stringWithFormat:@"%@/myFolder/",homePath] error:nil];
6.获取目录下的所有文件---------------------------------------------------------------------------------------------
//获取根目录
NSString* homePath = NSHomeDirectory();
//创建了一个文件管理器
NSFileManager* fileMgr = [NSFileManager defaultManager];
//拼接出想要创建的文件路径
NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/",homePath];
//获取当前目录下的所有文件,包括隐藏文件
NSArray* allFile = [fileMgr contentsOfDirectoryAtPath:filePath error:nil];
NSLog(@"%@",allFile);
//获取当前目录以及子目录的所有文件
NSArray* subAllFile = [fileMgr subpathsOfDirectoryAtPath:filePath error:nil];
7.文件的属性---------------------------------------------------------------------------------------------
//获取根目录
NSString* homePath = NSHomeDirectory();
//创建了一个文件管理器
NSFileManager* fileMgr = [NSFileManager defaultManager];
//拼接出想要创建的文件路径
NSString* filePath = [NSString stringWithFormat:@"%@/myFolder/3.txt",homePath];
NSDictionary* fileAttribute = [fileMgr fileAttributesAtPath:filePath traverseLink:YES];
//获取文件的属性
NSData* data = [fileAttribute objectForKey:NSFileModificationDate];
NSLog(@"文件的创建日期:%@",data);
//文件占多少字节
NSNumber * number = [fileAttribute objectForKey:NSFileSize];
NSLog(@"文件的大小:%@",number);
OC-文件操作的更多相关文章
- OC文件操作1
主要内容: 1)文件操作:对文件本身的操作(NSManager) 2)对文件内容的操作(NSHandle) 1.NSManager 创建一个单例的file manager的对象 //创建一个单例的fi ...
- OC文件操作(2)
NSFileManager 文件管理器完成文件的创建.移动.拷贝等管理操作 1.查询文件和目录 OC中查询路径下的目录主要分为浅度遍历和深度遍历. 浅度遍历 NSFileManager * ma ...
- OC文件操作(1)
1.文件的浅度遍历与深度遍历: //NSFileManager * fm = [[NSFileManager alloc]init];//创建文件管理器 //第一步创建一个文件管理器 NSError ...
- OC文件操作2
1.对文件本身的操作 NSManager 2.对文件内容的操作 NSHandle 文件句柄 NSFileHandle * fh = [NSFileHandle fileHandleForReading ...
- OC文件操作、获取文件属性
#import <Foundation/Foundation.h> //获取文件的属性 int main(int argc, const char * argv[]) { @autorel ...
- 归档NSKeyedArchiver解归档NSKeyedUnarchiver与文件管理类NSFileManager (文件操作)
========================== 文件操作 ========================== 一.归档NSKeyedArchiver 1.第一种方式:存储一种数据. // 归档 ...
- PHP文件操作系统----主要的文件操作函数
一.文件操作系统概述 1.概述: php中的文件操作系统主要是对文件和目录的操作.文件在windows系统下分为3种不同:文件.目录.未知,在linux/unix系统下分为7种不同:block.cha ...
- 【.NET深呼吸】Zip文件操作(1):创建和读取zip文档
.net的IO操作支持对zip文件的创建.读写和更新.使用起来也比较简单,.net的一向作风,东西都准备好了,至于如何使用,请看着办. 要对zip文件进行操作,主要用到以下三个类: 1.ZipFile ...
- 野路子出身PowerShell 文件操作实用功能
本文出处:http://www.cnblogs.com/wy123/p/6129498.html 因工作需要,处理一批文件,本想写C#来处理的,后来想想这个是PowerShell的天职,索性就网上各种 ...
- Node基础篇(文件操作)
文件操作 相关模块 Node内核提供了很多与文件操作相关的模块,每个模块都提供了一些最基本的操作API,在NPM中也有社区提供的功能包 fs: 基础的文件操作 API path: 提供和路径相关的操作 ...
随机推荐
- ionic3使用echart插件
安装 看官方文档可以知道ECharts可以在webpack中使用看这里,故我们可以使用npm下载安装到项目中 npm install echarts --save //下载ECharts npm in ...
- 使用.gitignore忽略文件
单个项目配置 在.git文件夹同目录下打开git bash,执行命令: touch .gitignore 生成“.gitignore”文件. 在”.gitignore” 文件里输入你要忽略的文件夹及其 ...
- 基于mondrain 的原理纠正特殊指标值
原文地址:http://www.cnblogs.com/qiaoyihang/p/7348385.html 下面有两张表 数学试卷成绩 表1 学号 省份 批次 学校 试卷成绩 数学试卷小题成绩 表2 ...
- python-绘图matplotlib
<Python编程:从入门到实践>读书笔记 1.使用plot()绘制简单的折线图 import matplotlib.pyplot as plt va=[1,2,3,4,5] sq=[1, ...
- Django——认证系统(Day72)
阅读目录 COOKIE 与 SESSION 用户认证 COOKIE 与 SESSION 概念 cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要“保持状态”,因 ...
- ubuntu下关于profile和bashrc中环境变量的理解
(0) 写在前面 有些名词可能需要解释一下.(也可以先不看这一节,在后面看到有疑惑再上来看相关解释) $PS1和交互式运行(running interactively): 简单地来说,交互式运行就是在 ...
- MapReduce概述
MapReduce 源自于Google的MapReduce论文,Hadoop MapReduce是Google MapReduce克隆版 MapReduce适合PB级以上海量数据的离线处理 MapRe ...
- Linux系统服务管理 服务管理
Linux独立服务管理 启动服务 systemctl start 服务名称.service 设置开机自启动 systemctl enable 服务名称.service 停止开机自启动 systemct ...
- CentOS6、7优化脚本完美版
#!/bin/bash SysVer=`cat /etc/redhat-release | awk -F'release' '{print $2}' | awk -F'[ .]+' '{print $ ...
- 本地存储(localStorage、sessionStorage、web Database)
一.sessionStorage和localStorage sessionStorage和localStorage两种方法都是当用户在inPut文本框中输入内容并点击保存数据按钮时保存数据,点击读取数 ...