您的位置:首页 > 移动开发 > IOS开发

iOS 通过路径对文件写入数据 读取数据

2016-07-21 16:27 465 查看
1获取沙盒不同文件的路径、

-(void)getFilePath{

//    1、获取程序的Home目录

    NSString *path =
NSHomeDirectory();

    NSLog(@"这是home目录%@",path);

//    2、获取Document目录

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

    NSLog(@"%@",documentpaths);

    NSString *documentpath = [documentpaths
objectAtIndex:0];

    NSLog(@"这是Docuemt目录%@",documentpath);

    //  3、获取Cache目录

    NSArray *cachePath =
NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask,
YES);

    NSString *cachePaths = [cachePath
objectAtIndex:0];

    NSLog(@"这是Cache目录%@",cachePaths);

//    4、获取Library目录

    NSArray *tempPath =
NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask,
YES);

    NSString *tempPaths = [tempPath
objectAtIndex:0];

    NSLog(@"这是Librayr目录%@",tempPaths);

//   5、获取Tmp目录

    NSString *tempDirectory =
NSTemporaryDirectory();

    NSLog(@"这是temp目录%@",tempDirectory); 
  

}
2将数据写入所创建的路径中

-(void)writeFileContent{

    //    将内容写入文件

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

    NSString *paths = [path
objectAtIndex:0];

//    NSArray *array = [[NSArray alloc]initWithObjects:@"内容",@"content", nil];

    NSArray *array =
@[@"abc",@"def",@"ggg",@10];

    NSString *filepath = [paths
stringByAppendingPathComponent:@"textFile.text"];

    [array writeToFile:filepath
atomically:YES];

}
3通过路径读取文件的数据、

-(void)readFile{

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

    NSString *docDir = [paths
objectAtIndex:0];

    NSString *filePath1 = [docDir
stringByAppendingPathComponent:@"textFile.text"];

    NSArray *array = [[NSArray
alloc] initWithContentsOfFile:filePath1];

    NSLog(@"%@",array);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  沙盒 数据