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

来源:互联网 发布:c语言创建多个进程 编辑:程序博客网 时间:2024/05/17 09:02

1获取沙盒不同文件的路径、

-(void)getFilePath{

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

    NSString *path =NSHomeDirectory();

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


//    2、获取Document目录

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

    NSLog(@"%@",documentpaths);

    NSString *documentpath = [documentpathsobjectAtIndex:0];

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

    //  3、获取Cache目录

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

    NSString *cachePaths = [cachePathobjectAtIndex:0];

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

//    4、获取Library目录

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

    NSString *tempPaths = [tempPathobjectAtIndex:0];

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

//   5、获取Tmp目录

    NSString *tempDirectory =NSTemporaryDirectory();

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

}

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

-(void)writeFileContent{

    //    将内容写入文件

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

    NSString *paths = [pathobjectAtIndex:0];

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

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

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

    [array writeToFile:filepathatomically:YES];

}

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

-(void)readFile{

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

    NSString *docDir = [pathsobjectAtIndex:0];

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

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

    NSLog(@"%@",array);

}

0 0
原创粉丝点击