iOS 关于文件的操作

时间:2023-03-09 06:32:56
iOS   关于文件的操作

最近做东西,遇到了使用文件方面的问题,花了点时间把文件研究了一下!

一  关于文件路径的生成

我用的方法是:

-(NSString*)dataFilePath

{

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

NSString * documentsDirectory  = [paths objectAtIndex:0];

NSLog(@"—0——%@",documentsDirectory);

return [documentsDirectory stringByAppendingPathComponent:@"cataog.db”];

}

但是NSDocumentDirectory是指程序中对应的Documents 路径,

NSDocumentationDiretory是对应于程序中的Library/Documentation 路径 ,这个路径是没有读写权限的,所以即使自己所查找的文件不存在,也看不到文件的自动生成!

所以以上应改为:

-(NSString*)dataFilePath

{

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString * documentsDirectory  = [paths objectAtIndex:0];

NSString *path =[documentsDirectory stringByAppendingPathComponent:@"cataog.db"];

NSLog(@"*****%@",path);

return path;

}

这样的话就可以了!

下面讨论一下对文件的操作:

对文件的操作,核心函数是:NSSearchPathForDirectoriesInDomains

iOS 看开发是在沙盒中开发的,对一些部分的文件的读写进行了限制,只能在几个目录下读写文件:

(1)Documents :应用中用户数据可以存放在这里,iTunes的数据备份和恢复的时候会包括此目录

(2)tmp:存放临时文件的,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除

(3)Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会再应用退出删除对于文件的操作

二   利用NSSearchPathForDirectoriesInDomains 建立文件,并可以向内写入数据

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString * documentsDirectory  = [paths objectAtIndex:0];

NSString *content=@"write data into myFile”;

NSData *contentData=[content dataUsingEncoding:NSASCIIStringEncoding];

if ([contentData writeToFile:fileName atomically:YES]) {
    NSLog(@">>write ok."); 
}

如果要想文件内写入文字的话,需要改变编码方式:

NSString *contentChinese=@"写入汉字信息到文件”;

NSData *contentChineseData=[contentChinese dataUsingEncoding:NSUnicodeStringEncoding];

if ([contentData writeToFile:fileName atomically:YES]) {
    NSLog(@">>写入成功.");

}

如果要指定其他文件目录,比如Caches目录,需要更换目录常量为:NSCachesDirectory

为大家列出:

常量                                                                      目录       
NSDocumentDirectory                        <Application_Home>/Documents       
NSCachesDirectory                             <Application_Home>/Library/Caches       NSApplicationSupportDirectory          <Application_Home>/Library/ApplicationSupport

  另外我们在开发中也需要用到一些资源文件:

NSString *Path = [[NSBundle mainBundle] 
                        pathForResource:@"f" 
                        ofType:@"txt"]; 
NSString *Content=[NSString stringWithContentsOfFile:Path encoding:NSUTF8StringEncoding error:nil]; 
NSLog(@" path: %@ \nfile content:%@",Path,Content);