[iOS翻译]《iOS 7 Programming Cookbook》:iOS文件与文件夹管理(上)
简介:
iOS基于OS X,而OSX本身基于Unix操作系统。在iOS里面,操作系统的完全路径结构是不可见的,因为每个APP的数据都存储自身的沙盒里面。沙盒环境实际上听起来像这样:一个只允许当前APP访问的文件夹目录。每个APP都有自身的沙盒文件夹,并且沙盒文件夹下的子文件夹只有当前APP能够访问。
当一个iOS APP在设备上安装后,系统为其创建的文件夹结构如下:

- XXX.app
- 即Main Bundle
- Documents/
- 存储用户创建的内容
- Library/
- 存储缓存文件、偏好设置等等
每个应用的根文件夹包含各种其他文件夹,下面是一些解释:
- Library/Caches/
- 存储重复创建的缓存文件
- 磁盘空间不足且应用不在运行状态时,该目录下文件可能会被删除,切记
- Library/Preferences/
- 存储偏好设置
- Library/Application Support/
- 不会自动创建
- tmp/
- 临时文件
现在你知道当APP在设备上安装后,系统为你创建了哪些文件夹。下一步你也许会想知道,如何找到这些文件夹的路径。
/*
本文翻译自《iOS 7 Programming Cookbook》一书的第14章“Files and Folder Management ”,想体会原文精髓的朋友请支持原书正版。
——————(博客园、新浪微博)葛布林大帝
*/
目录:
一. 获取常用文件夹的路径
二. 写入和读取文件
三. 创建文件夹
四. 枚举文件/文件夹
五. 删除文件/文件夹
六. 存储对象到文件
本书源代码:https://github.com/oreillymedia/iOS7_Programming_Cookbook
一、获取常用文件夹的路径
问题:
你想找到可用文件夹的路径
解决方案:
使用NSFileManager类的实例方法URLsForDirectory:inDomains:
讨论:
NSFileManager类提供了许多与文件/文件夹相关的操作,我不建议使用这个类提供的defaultManager类方法来进行文件管理,因为它不是线程安全的。
NSFileManager类的URLsForDirectory:inDomains:实例方法常被用来搜索iOS文件系统的指定目录,其中两个参数如下:
- URLsForDirectory:
- 想要搜索的目录
- 参数值为NSSearchPathDirectory类型的枚举
- inDomains
- 想要寻找的指定目录
- 参数值为NSSearchPathDomainMask类型的枚举
1.Documents文件夹
假设你想要找出Documents文件夹的路径,代码如下:
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask]; if ([urls count] > ){
NSURL *documentsFolder = urls[];
NSLog(@"%@", documentsFolder);
} else {
NSLog(@"Could not find the Documents folder.");
}
运行代码,你应该得到了Document文件夹的路径。现在我们来看看URLsForDirectory:inDomains:方法的常用参数:
- URLsForDirectory
- NSLibraryDirectory
- Library文件夹
- NSCachesDirectory
- Caches文件夹
- NSDocumentDirectory
- Documents文件夹
- NSLibraryDirectory
- inDomains
- NSUserDomainMask
- 在当前用户文件夹里执行指定搜索
- 在OS X里,这个文件夹为 ~/
- NSUserDomainMask
2.Caches文件夹
使用这个方法,你也可以找到Caches文件夹,以此类推:
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *urls = [fileManager URLsForDirectory:NSCachesDirectory
inDomains:NSUserDomainMask]; if ([urls count] > ){
NSURL *cachesFolder = urls[];
NSLog(@"%@", cachesFolder);
} else {
NSLog(@"Could not find the Caches folder.");
}
3.tmp文件夹
如果你想要找到tmp文件夹,使用C函数NSTemporaryDirectory():
NSString *tempDirectory = NSTemporaryDirectory();
NSLog(@"Temp Directory = %@", tempDirectory);
二、写入和读取文件
问题:
你想存储信息到磁盘(如text、data、images等等)
解决方案:
Cocoa类允许你存储信息,例如NSString、UIImage和NSData,所有公开的实例方法允许你存储这些数据到指定的路径。
讨论
为了存储text到磁盘,假设把text作为一个NSString变量来存储,可以使用这个类的实例方法writeToFile:atomically:en coding:error:,参数如下:
- writeToFile
- 要写入的路径,类型为NSString
- atomically
- BOOL类型。如果设为YES,会写入文件到一个临时空间,并且在存储到目的地后移除临时文件
- encoding
- 编码模式,通常使用NSUTF8StringEncoding
- error
- 存储失败时,使用一个指针指向NSError对象
1.存储NSString
例如,如果想要临时存储一些text,并不需要备份,代码如下:
NSString *someText = @"Random string that won't be backed up.";
NSString *destinationPath =
[NSTemporaryDirectory()
stringByAppendingPathComponent:@"MyFile.txt"]; NSError *error = nil;
BOOL succeeded = [someText writeToFile:destinationPath
atomically:YES
encoding:NSUTF8StringEncoding
error:&error]; if (succeeded) {
NSLog(@"Successfully stored the file at: %@", destinationPath);
} else {
NSLog(@"Failed to store the file. Error = %@", error);
}
2.从文件读取NSString
完成上面的存储后,你可以使用NSString类的stringWithContentsOfFile:encoding:error:类方法获取指定文件的路径。
如果你想从一个文件读取NSString内容,可以使用NSString类的实例方法initWithContentsOfFile:encoding:error:,代码如下:
- (BOOL) writeText:(NSString *)paramText toPath:(NSString *)paramPath{
return [paramText writeToFile:paramPath
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
}
- (NSString *) readTextFromPath:(NSString *)paramPath{
return [[NSString alloc] initWithContentsOfFile:paramPath
encoding:NSUTF8StringEncoding
error:nil];
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"MyFile.txt"];
if ([self writeText:@"Hello, World!" toPath:filePath]){
NSString *readText = [self readTextFromPath:filePath];
if ([readText length] > ){
NSLog(@"Text read from disk = %@", readText);
}else {
NSLog(@"Failed to read the text from disk.");
}
} else {
NSLog(@"Failed to write the file.");
}
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor]; [
self.window makeKeyAndVisible]; return YES;
}
上面创建了两个便利方法,允许我们从指定位置写入和读取文本。
如果你想使用NSURL的实例,可以使用writeToURL:atomically:encoding:error:实例方法来代替。
3.写入和读取NSArray
Foundation其他类的写入方法类似NSString,对于NSArray,可以使用实例方法writeToFile:atom ically:。
为了从磁盘读取array的内容,可以使用初始化方法initWithContentsOfFile:,代码如下:
NSString *filePath = [NSTemporaryDirectory()
stringByAppendingPathComponent:@"MyFile.txt"]; NSArray *arrayOfNames = @[@"Steve", @"John", @"Edward"];
if ([arrayOfNames writeToFile:filePath atomically:YES]){
NSArray *readArray = [[NSArray alloc] initWithContentsOfFile:filePath];
if ([readArray count] == [arrayOfNames count]){
NSLog(@"Read the array back from disk just fine.");
} else {
NSLog(@"Failed to read the array back from disk.");
}
} else {
NSLog(@"Failed to save the array to disk.");
}
NSArray的实例方法writeToFile:atomically:可以存储包含下列类型对象的数组:
- NSString
- NSDictionary
- NSArray
- NSData
- NSNumber
- NSData
4.写入和读取NSDictionary
字典的读写操作与数组十份相似,代码如下:
NSString *filePath = [NSTemporaryDirectory()
stringByAppendingPathComponent:@"MyFile.txt"];
NSDictionary *dict = @{
@"first name" : @"Steven",
@"middle name" : @"Paul",
@"last name" : @"Jobs",
}; if ([dict writeToFile:filePath atomically:YES]){
NSDictionary *readDictionary = [[NSDictionary alloc]
initWithContentsOfFile:filePath]; /* Now compare the dictionaries and see if the one we read from disk is the same as the one we saved to disk */
if ([readDictionary isEqualToDictionary:dict]){
NSLog(@"The file we read is the same one as the one we saved.");
} else {
NSLog(@"Failed to read the dictionary from disk.");
}
} else {
NSLog(@"Failed to write the dictionary to disk.");
}
5.char与NSData
想要写入一个char类型,可以使用NSData,代码如下:
NSString *filePath = [NSTemporaryDirectory()
stringByAppendingPathComponent:@"MyFile.txt"]; char bytes[] = {'a', 'b', 'c', 'd'}; NSData *dataFromBytes = [[NSData alloc] initWithBytes:bytes
length:sizeof(bytes)]; if ([dataFromBytes writeToFile:filePath atomically:YES]){
NSData *readData = [[NSData alloc] initWithContentsOfFile:filePath];
if ([readData isEqualToData:dataFromBytes]){
NSLog(@"The data read is the same data as was written to disk.");
} else {
NSLog(@"Failed to read the data from disk.");
}
} else {
NSLog(@"Failed to save the data to disk.");
}
[iOS翻译]《iOS 7 Programming Cookbook》:iOS文件与文件夹管理(上)的更多相关文章
- [iOS翻译]《iOS 7 Programming Cookbook》:iOS文件与文件夹管理(下)
三. 创建文件夹 问题: 你想创建文件夹到磁盘,存储一些文件到里面 解决方案: 使NSFileManager类的实例方法createDirectoryAtPath:withIntermediateDi ...
- [book] iOS 8 Swift Programming Cookbook
iOS 8 Swift Programming Cookbook 资源地址 http://pan.baidu.com/s/1c0hn1Gc 书籍介绍 源码截图 书籍截图
- iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载+使用输出流代替文件句柄
前言:本篇讲解,在前篇iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载的基础上,使用输出流代替文件句柄实现大文件断点续传. 在实际开发中,输入输出流用的比较少,但 ...
- IOS证书/私钥/代码签名/描述文件
1. 相关资源 (1) 钥匙串程序(常用工具->钥匙串),用于创建证书请求.安装证书.导出私钥等 (2) IOS开发中心:https://developer.apple.com/de ...
- iOS开发——Swift篇&文件,文件夹操作
文件,文件夹操作 ios开发经常会遇到读文件,写文件等,对文件和文件夹的操作,这时就可以使用NSFileManager,NSFileHandle等类来实现. 下面总结了各种常用的操作: 1,遍 ...
- iOS Dev (20) 用 AVAudioPlayer 播放一个本地音频文件
iOS Dev (20) 用 AVAudioPlayer 播放一个本地音频文件 作者:CSDN 大锐哥 博客:http://blog.csdn.net/prevention 步骤 第一步:在 Proj ...
- iOS Dev (21) 用 AVPlayer 播放一个本地音频文件
iOS Dev (21) 用 AVPlayer 播放一个本地音频文件 作者:CSDN 大锐哥 博客:http://blog.csdn.net/prevention 前言 这篇文章与上一篇极其相似,要注 ...
- iOS 11开发教程(六)iOS11Main.storyboard文件编辑界面
iOS 11开发教程(六)iOS11Main.storyboard文件编辑界面 在1.2.2小节中提到过编辑界面(Interface builder),编辑界面是用来设计用户界面的,单击打开Main. ...
- iOS开发小技巧--边接受数据边写入文件的两种方法
一.NSFileHanle 使用注意点:在往文件写入数据时,必须创建一个空的文件 指定文件写入的方式 -- 覆盖还是追加 最后记得关闭 <1>代码是在大文件传输的练习中截取的.写入数据之前 ...
随机推荐
- Spring(一)简述
一.Spring简述 一段费话 Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2 ...
- Android bitmap高效显示和优化
第一部分:Bitmap高效显示 应用场景:有时候我们想在界面上显示一个网络图片或者显示一张本地的图片,但是图片本身是很大的有几兆,但是显示的位置很小或者说我们可以用更小的图片来满足这样的需求,如果把整 ...
- OC语言-02-OC语言-基础知识
一.基础语法 1> OC语言和C语言 C语言是面向过程的语言,OC语言是面向对象的语言 OC语言继承了C语言,并增加了面向对象的思想 以下内容只介绍OC语言与C语言的不同之处 2> 关键字 ...
- JSP基础--JAVA遇见HTML
1.手工编写第一个WEB应用程序 2.默认访问服务器网页首页欢迎界面是 index.jsp,就是网页链接访问其所在的文件夹目录,不访问这个文件,也会自动访问的.如果这个文件夹目录下没有index.js ...
- GET/POST请求的使用《极客学院 --AFNetworking 2.x 网络解析详解--2》学习笔记
AFNetworking是开源代码排名第一的开源库. GET请求的请求正文 一般都是明文显示的,携带的数据量小. POST用于处理复杂的业务,并不用明文的请求,其实POST请求可以携带更多的参数,只 ...
- [LoadRunner]性能测试实践_Hessian协议脚本编写
第一步,新建LR的脚本,选择Java Vuser协议: 第二步,编写hessian测试脚本,如下: import lrapi.lr; import java.net.MalformedURLExcep ...
- windows下使用tomcat部署网站
一.配置过程: 1. 配置java环境(之前已装过,跳过此步骤) 2. 下载tomcat (1)找到支持此java版本的tomcat版本: (2)下载与当前系统对应的安装文件 http://tom ...
- 关于Redis info的参数总结
Redis官网对 info 已经讲解的比较清楚的,参考文档 .可以看到,info的输出结果是分几块的,有Servers.Clients.Memory等等,通过info后面接这些参数,可以指定输出某一块 ...
- DataTable转List<Model>通用类
/// <summary> /// DataTable转List<Model>通用类[实体转换辅助类] /// </summary> public class Mo ...
- Hibernate基于注解方式配置来实现实体和数据库之间存在某种映射关系
实体和数据库之间存在某种映射关系,hibernate根据这种映射关系完成数据的存取.在程序中这种映射关系由映射文件(*.hbm.xml)或者java注解(@)定义. 本文以java注解的形式总结映射关 ...