iOS文件管理

iOS开发-文件管理(一)

一、iOS中的沙盒机制

iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一般存放着程序包文件(可执行文件)、图片、音频、视频、plist文件、sqlite数据库以及其他文件。

每个应用程序都有自己的独立的存储空间(沙盒)

一般来说应用程序之间是不可以互相访问

模拟器沙盒的位置

/User/userName/Library/Application Support/iPhone Simulator

当我们创建应用程序时,在每个沙盒中含有三个文件,分别是Document、Library和temp。

Document:一般需要持久的数据都放在此目录中,可以在当中添加子文件夹,iTunes备份和恢复的时候,会包括此目录。

Library:设置程序的默认设置和其他状态信息

temp:创建临时文件的目录,当iOS设备重启时,文件会被自动清除

获取沙盒目录

获取程序的根目录(home)目录

NSString *homePath = NSHomeDirectory()

获取Document目录

NSArray

*paths = NSSearchPathDorDirectoriesInDomains(NSDocumentDicrectory,,

NSUserDomainMark,

YES);

NSString *docPath = [paths lastObject];

获取Library目录

NSArray

*paths = NSSearchPathForDirectoriseInDomains(NSLibraryDirectory,

NSUserDomainMask,

YES);

NSString *docPath = [paths lastObject];

获取Library中的Cache

NSArray

*paths = NSSearchPathForDirectoriseInDomains(NSCachesDirectory,

NSUserDomainMask,

YES);

NSString *docPath = [paths lastObject];

获取temp路径

NSString *temp = NSTemporaryDirectory( );

二、NSString类路径的处理方法

文件路径的处理

NSString *path = @"/Uesrs/apple/testfile.txt"

常用方法如下

获得组成此路径的各个组成部分,结果:("/","User","apple","testfile.txt")

- (NSArray *)pathComponents;

提取路径的最后一个组成部分,结果:testfile.txt

- (NSString *)lastPathComponent;

删除路径的最后一个组成部分,结果:/Users/apple

- (NSString *)stringByDeletingLastPathCpmponent;

将path添加到先邮路径的末尾,结果:/Users/apple/testfile.txt/app.txt

- (NSString *)stringByAppendingPathConmponent:(NSString *)str;

去路径最后部分的扩展名,结果:text

- (NSString *)pathExtension;

删除路径最后部分的扩展名,结果:/Users/apple/testfile

- (NSString *)stringByDeletingPathExtension;

路径最后部分追加扩展名,结果:/User/apple/testfile.txt.jpg

- (NSString *)stringByAppendingPathExtension:(NSString *)str;

三、NSData

NSData是用来包装数据的

NSData存储的是二进制数据,屏蔽了数据之间的差异,文本、音频、图像等数据都可用NSData来存储

NSData的用法

1.NSString与NSData互相转换

NSData->

NSString

NSString *aString = [[NSString alloc]

initWithData:adataencoding:NSUTF8StringEncoding];

NSString->NSData                                                                                      NSString *aString = @"1234abcd";

NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];

将data类型的数据,转成UTF8的数据

+(NSString *)dataToUTF8String:(NSData *)data

{

NSString *buf = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

return [buf autorelease];

}

将string转换为指定编码

+(NSString *)changeDataToEncodinString:(NSData *)data encodin:(NSStringEncoding )encodin{

NSString *buf = [[[NSString alloc] initWithData:data encoding:encodin] autorelease];

return buf;

}

2. NSData 与 UIImage

NSData->UIImage

UIImage *aimage = [UIImage imageWithData: imageData];

//例:从本地文件沙盒中取图片并转换为NSData

NSString *path = [[NSBundle mainBundle] bundlePath];

NSString *name = [NSString stringWithFormat:@"ceshi.png"];

NSString *finalPath = [path stringByAppendingPathComponent:name];

NSData *imageData = [NSData dataWithContentsOfFile: finalPath];

UIImage *aimage = [UIImage imageWithData: imageData];

3.NSData与NSArray  NSDictionary

+(NSString *)getLocalFilePath:(NSString *) fileName

{

return [NSString stringWithFormat:@"%@/%@%@", NSHomeDirectory(),@“Documents”,fileName];

}

包括将NSData写进Documents目录

从Documents目录读取数据

在进行网络数据通信的时候,经常会遇到NSData类型的数据。在该数据是dictionary结构的情况下,系统没有提供现成的转换成NSDictionary的方法,为此可以通过Category对NSDictionary进行扩展,以支持从NSData到NSDictionary的转换。声明和实现如下:

+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data {

CFPropertyListRef list = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data, kCFPropertyListImmutable, NULL);

if(list == nil) return nil;

if ([(id)list isKindOfClass:[NSDictionary class]]) {

return [(NSDictionary *)list autorelease];

}

else {

CFRelease(list);

return nil;

}

}

四、文件管理常用方法

NSFileManager

创建一个文件并写入数据- (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;

从一个文件中读取数据- (NSData *)contentsAtPath:(NSString *)path;

scrPath路径上的文件移动到dstPath路径上,注意这里的路径是文件路径而不是目录- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **) error;

scrPath路径上的文件复制到dstPath路径上- (BOOL)copyItemAtPath:(NSString *)scrPath toPath:(NSString *)dstPath error:(NSError **) error;

比较两个文件的内容是否一样- (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2;

文件时候存在- (BOOL)fileExistsAtPath:(NSString *)path;

移除文件- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **) error;

创建文件管理

NSFileManager

*fileManager = [NSFileManager defaultManager];

NSString *path = [NSHomeDirectory( )

stringByAppendingPathComponent:@"holyBible.txt"];

NSString *text = @"abcdefg";

将字符串转成NSData类型NSData *data = [text dataUsingEncoding: NSUTF8StringEncoding];

写入文件BOOL success = [fileManager createFileAtPath:path contents:data attributes:nil];

创建文件夹

NSString

*filePath = [path stringByAppendingPathComponent:@"holyBible.txt"];

NSString

*contect = @"abcdefg";

BOOL success = [fm createFileAtPath:filePath contents:[content

dataUsingEncoding: NSUTF8StringEncoding] attributes:nil];

NSFileManager-读取内容NSData *fileData = [fileManager contentsAtPath:filePath];                                   NSString *content = [[NSString alloc] initWithData:fileData dataUsingEncoding: NSUTF8StringEncoding];

NSData-读取内容NSString *filePath = [path stringByAppendingPathComponent:@"holyBible.txt"];     NSData *data = [NSData dataWithContentOfFile:filePath];

NSString-读取内容NSString *filePath = [path stringByAppendingPathComponent:@"holyBible.txt"];     NSString *content = [[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

移动、复制文件

移动文件(重命名)NSString *toPath = [NSHomeDirectory( ) stringByAppendingPathComponent:@"hellogod/New Testament.txt"];                                                                              [fm createDirectoryAtPath:[toPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];                                                   NSError *error;                                                                                             BOOL isSuccess = [fm moveItemAtPath:filePath toPath:toPath error:&error];

复制文件(重命名)NSString *copyPath = [NSHomeDirectory( ) stringByAppendingPathComponent:@"备份/Old Testament.txt"];[fm createDirectoryAtPath:[toPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];                                                   BOOL success = [fm copyItemAtPath:toPath toPath:toPath error:nil];

删除文件、获取文件大小

判断文件是否存在和删除文件if([fm fileExistsAtPath])                                                                                     {                                                                                                                    if ([fm removeItemAtPath:copyPath])                                                                {                                                                                                                   NSLog(@"remove success");                                                                            }                                                                                                                  }

获取文件大小NSFileManager *fileManager = [NSFileManager defaultManager];                         获得文件的属性字典                                                                                         NSDictionary *attrDic = [fileManager attributesOfItemAtpath:sourcePath error:nil];  NSNumber *fileSize = [attrDic objectForKey:NSFileSize];

获取目录文件信息NSFileManager *fileManager = [NSFileManager defaultManager];                         NSString *enuPath = [NSHomeDirectoty( ) stringByAppendingPathComponent:@"Test"];                                                                                                           NSDictionaryEnumerator *dirEnum = [fileManager enumeratorAtPath:enuPath];     NSString *path = nil;                                                                                      while ((path = [dirEnum nextObject]} != nil)                                                        {                                                                                                                  NSLog(@"%@",path);                                                                                        }


iOS开发-文件管理(二)

五、Plist文件

String方式添加

NSString *path = [NSHomeDirectory( )  stringByAppendingPathComponent:@"Array.plist"];

NSString *content = @"abcd";

[contect writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

Array方式添加

NSString *path = [NSHomeDirectory( )  stringByAppendingPathComponent:@"Array.plist"];

[NSArray *array = [[NSArray alloc] initWithObjects:@"123", @"798",@"000",nil];       [array writeToFile:path atomically:YES];

Dictionary方式添加

NSString *path = [NSHomeDirectory( )  stringByAppendingPathComponent:@"Dic.plist"];

NSDictionary *dic = [NSDictionary alloc] initWithObjects:@"first",@"second",@"third"forKeys:@"123",@"456",@"798"];                                                                       [dic writeToFile:path atomically:YES];

数组、字典只能将BOOL、NSNumber、NSString、NSData、NSDate、NSArray、NSDictionary写入属性列表plist文件

六、读取文件类和常用方法

NSFileHandle类主要对文件内容进行读取和写入操作

NSFileManager类主要对文件的操作(删除、修改、移动、复制等等)

常用处理方法

+ (id)fileHandleForReadingAtPath:(NSString *)path  打开一个文件准备读取

+ (id)fileHandleForWritingAtPath:(NSString *)path  打开一个文件准备写入

+ (id)fileHandleForUpdatingAtPath:(NSString *)path  打开一个文件准备更新

-  (NSData *)availableData; 从设备或通道返回可用的数据

-  (NSData *)readDataToEndOfFile; 从当前的节点读取到文件的末尾

-  (NSData *)readDataOfLength:(NSUInteger)length; 从当前节点开始读取指定的长度数据

-  (void)writeData:(NSData *)data; 写入数据

-  (unsigned long long)offsetInFile;  获取当前文件的偏移量

-  (void)seekToFileOffset:(unsigned long long)offset; 跳到指定文件的偏移量

-  (unsigned long long)seekToEndOfFile; 跳到文件末尾

-  (void)truncateFileAtOffset:(unsigned long long)offset; 将文件的长度设为offset字节

-  (void)closeFile;  关闭文件

向文件追加数据

NSString *homePath  = NSHomeDirectory( );

NSString *sourcePath = [homePath stringByAppendingPathConmpone:@"testfile.text"];

NSFileHandle

*fielHandle = [NSFileHandle

fileHandleForUpdatingAtPath:sourcePath];

[fileHandle seekToEndOfFile];  将节点跳到文件的末尾

NSString *str = @"追加的数据"

NSData* stringData  = [str dataUsingEncoding:NSUTF8StringEncoding];

[fileHandle writeData:stringData]; 追加写入数据

[fileHandle closeFile];

定位数据

NSFileManager *fm = [NSFileManager defaultManager];

NSString *content = @"abcdef";

[fm

createFileAtPath:path contents:[content

dataUsingEncoding:NSUTF8StringEncoding]

attributes:nil];

NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];

NSUInteger length = [fileHandle availabelData] length]; 获取数据长度

[fileHandle seekToFileOffset;length/2]; 偏移量文件的一半

NSData *data = [fileHandle readDataToEndOfFile];

[fileHandle closeFile];

复制文件

NSFileHandle *infile, *outfile; 输入文件、输出文件

NSData *buffer; 读取的缓冲数据

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *homePath = NSHomeDirectory( );

NSString

*sourcePath = [homePath

stringByAppendingPathComponent:@"testfile.txt"];  源文件路

NSString *outPath = [homePath stringByAppendingPathComponent:@"outfile.txt"]; 输出文件路径

BOOL sucess  = [fileManager createFileAtPath:outPath contents:nil attributes:nil];

if (!success)

{

return N0;

}

infile = [NSFileHandle fileHandleForReadingAtPath:sourcePath]; 创建读取源路径文件

if (infile == nil)

{

return NO;

}

outfile

= [NSFileHandle

fileHandleForReadingAtPath:outPath]; 创建病打开要输出的文

if (outfile == nil)

{

return NO;

}

[outfile truncateFileAtOffset:0]; 将输出文件的长度设为0

buffer = [infile readDataToEndOfFile];  读取数据

[outfile writeData:buffer];  写入输入

[infile closeFile];        关闭写入、输入文件

[outfile closeFile];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,829评论 1 331
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,603评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,846评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,600评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,780评论 3 272
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,695评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,136评论 2 293
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,862评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,453评论 0 229
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,942评论 2 233
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,347评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,790评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,293评论 3 221
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,839评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,448评论 0 181
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,564评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,623评论 2 249

推荐阅读更多精彩内容

  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    tzhtodd阅读 1,232评论 0 2
  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    绚雨蓝了个枫阅读 3,980评论 0 2
  • 一、iOS中的沙盒机制 •iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它...
    舒城8中阅读 2,339评论 0 6
  • iOS文件管理系统NSFileManager使用详解 1,找到自己的程序的目录: NSHomeDirectory(...
    lhg_serven阅读 10,973评论 0 4
  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    1d5cb7cff98d阅读 1,659评论 0 0