iOS中对文件的操作
转自:http://marshal.easymorse.com/archives/3340
iOS中对文件的操作
因为应用是在沙箱(sandbox)中的,在文件读写权限上受到限制,只能在几个目录下读写文件:
- Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
- tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
- Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除
在Documents目录下创建文件
代码如下:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory
, NSUserDomainMask
, YES);
NSLog(@"Get document path: %@",[paths objectAtIndex:0]);NSString *fileName=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"];
NSString *content=@"a";
NSData *contentData=[content dataUsingEncoding:NSASCIIStringEncoding];
if ([contentData writeToFile:fileName atomically:YES]) {
NSLog(@">>write ok.");
}
可以通过ssh登录设备看到Documents目录下生成了该文件。
上述是创建ascii编码文本文件,如果要带汉字,比如:
NSString *fileName=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"myFile"];
NSString *content=@"更深夜静人已息";
NSData *contentData=[content dataUsingEncoding:NSUnicodeStringEncoding];
if ([contentData writeToFile:fileName atomically:YES]) {
NSLog(@">>write ok.");
}
如果还用ascii编码,将不会生成文件。这里使用NSUnicodeStringEncoding就可以了。
通过filezilla下载到创建的文件打开,中文没有问题:
在其他目录下创建文件
如果要指定其他文件目录,比如Caches目录,需要更换目录工厂常量,上面代码其他的可不变:
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory
, NSUserDomainMask
, YES);
使用NSSearchPathForDirectoriesInDomains只能定位Caches目录和Documents目录。
tmp目录,不能按照上面的做法获得目录了,有个函数可以获得应用的根目录:
NSHomeDirectory()
也就是Documents的上级目录,当然也是tmp目录的上级目录。那么文件路径可以这样写:
NSString *fileName=[NSHomeDirectory() stringByAppendingPathComponent:@"tmp/myFile.txt"];
或者,更直接一点,可以用这个函数:
NSTemporaryDirectory()
不过生成的路径将可能是:
…/tmp/-Tmp-/myFile.txt
使用资源文件
在编写应用项目的时候,常常会使用资源文件,比如:
安装到设备上后,是在app目录下的:
以下代码演示如何获取到文件并打印文件内容:
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:@"f"
ofType:@"txt"];
NSString *myFileContent=[NSString stringWithContentsOfFile:myFilePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"bundel file path: %@ \nfile content:%@",myFilePath,myFileContent);
代码运行效果:
[self.fileManagerfileExistsAtPath:isDirectory:];
用于执行一般的文件系统操作 (reading and writing is done via NSData, et. al.).主要功能包括:从一个文件中读取数据;向一个文件中写入数据;删除文件;复制文件;移动文件;比较两个文件的内容;测试文件的存在性;读取/更改文件的属性... ...
Just alloc/init an instance and start performing operations. Thread safe.
- 常见的NSFileManager处理文件的方法如下:
NSFileManager *fileManager = [[NSFileManager alloc]init]; //最好不要用defaultManager。
NSData *myData = [fileManager contentsAtPath:path]; // 从一个文件中读取数据
[fileManager createFileAtPath:path contents:myData attributes:dict];//向一个文件中写入数据,属性字典允许你制定要创建
[fileManager removeItemAtPath:path error:err];
[fileManager moveItemAtPath:path toPath:path2 error:err];
[fileManager copyItemAtPath:path toPath:path2 error:err];
[fileManager contentsEqualAtPath:path andPath:path2];
[fileManager fileExistsAtPath:path]; ... ...
- 常见的NSFileManager处理目录的方法如下:
[fileManager currentDirectoryPath];
[fileManager changeCurrentDirectoryPath:path];
[fileManager copyItemAtPath:path toPath:path2 error:err];
[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:err];
[fileManager fileExistsAtPath:path isDirectory:YES];
[fileManager enumeratorAtPath:path]; //获取目录的内容列表。一次可以枚举指定目录中的每个文件。 ... ...
Has a delegate with lots of “should” methods (to do an operation or proceed after an error).And plenty more. Check out the documentation.
1、文件的创建
-(IBAction) CreateFile { //对于错误信息 NSError *error; // 创建文件管理器 NSFileManager *fileMgr = [NSFileManager defaultManager]; //指向文件目录 NSString *documentsDirectory= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
[[NSFileManager defaultManager] createDirectoryAtPath: [NSString stringWithFormat:@"%@/myFolder", NSHomeDirectory()] attributes:nil]; // File we want to create in the documents directory我们想要创建的文件将会出现在文件目录中 // Result is: /Documents/file1.txt结果为:/Documents/file1.txt NSString *filePath= [documentsDirectory stringByAppendingPathComponent:@"file2.txt"]; //需要写入的字符串 NSString *str= @"iPhoneDeveloper Tips\nhttp://iPhoneDevelopTips,com"; //写入文件 [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]; //显示文件目录的内容 NSLog(@"Documentsdirectory: %@",[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]); |
2、对文件重命名
对一个文件重命名 想要重命名一个文件,我们需要把文件移到一个新的路径下。下面的代码创建了我们所期望的目标文件的路径,然后请求移动文件以及在移动之后显示文件目录。 //通过移动该文件对文件重命名 NSString *filePath2= [documentsDirectory stringByAppendingPathComponent:@"file2.txt"]; //判断是否移动 if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES) NSLog(@"Unable to move file: %@", [error localizedDescription]); //显示文件目录的内容 NSLog(@"Documentsdirectory: %@", [fileMgr contentsOfDirectoryAtPath:documentsDirectoryerror:&error]); |
3、删除一个文件
这些示例能教你的,仅仅只是文件处理上的一些皮毛。想要获得更全面、详细的讲解,你就需要掌握NSFileManager文件的知识。 |
4、删除目录下所有文件
//获取文件路径 NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [document stringByAppendingPathComponent:@"Attchments"];
[manager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil]; } } --清除附件 |
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath])
{
//do some thing
}
附:
-(NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:@"data.plist"];
}
============================================================================
NSFileHandle类允许更有效地使用文件。
可以实现如下功能:
1、打开一个文件,执行读、写或更新(读写)操作;
2、在文件中查找指定位置;
3、从文件中读取特定数目的字节,或将特定数目的字节写入文件中
另外,NSFileHandle类提供的方法也可以用于各种设备或套接字。一般而言,我们处理文件时都要经历以下三个步骤:
1、打开文件,获取一个NSFileHandle对象(以便在后面的I/O操作中引用该文件)。
2、对打开文件执行I/O操作。
3、关闭文件。
NSFileHandle *fileHandle = [[NSFileHandle alloc]init];
fileHandle = [NSFileHandle fileHandleForReadingAtPath:path]; //打开一个文件准备读取
fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];
fileData = [fileHandle availableData]; // 从设备或者通道返回可用的数据
fileData = [fileHandle readDataToEndOfFile];
[fileHandle writeData:fileData]; //将NSData数据写入文件
[fileHandle closeFile]; //关闭文件 ... ...
注:NSFileHandle类没有提供创建文件的功能,所以必须使用NSFileManager来创建文件posted on 2015-06-29 21:49 cynthia116 阅读(547) 评论(0) 编辑 收藏 举报