沙盒、文件以及文件夹的操作
2016-05-01 19:04
316 查看
NSData
// 把NSString转化成NSData NSData *dataContents = [str dataUsingEncoding:NSUTF8StringEncoding];
沙盒
//沙盒路径 //方法一(主目录文件) NSString *sandBoxPath = NSHomeDirectory(); NSLog(@"%@", sandBoxPath); //方法二 (iOS开发mac开发均可用) NSArray *sandBoxPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //拼接方法一(拼接前加/) NSString *path1 = [sandBoxPath stringByAppendingString:@"/Documents"]; NSLog(@"%@", path1); //拼接方法二(不用加/) NSString *path2 = [sandBoxPath stringByAppendingPathComponent:@"file.txt"]; [[NSFileManager defaultManager] createFileAtPath:path2 contents:nil attributes:nil]; NSLog(@"path2:%@", path2);
文件以及文件夹操作
NSFileManager *fileManeger = [NSFileManager defaultManager]; NSString *str = @"hello world"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]; NSString *homePath = NSHomeDirectory(); //创建文件 NSString *filePath = [homePath stringByAppendingPathComponent:@"Desktop/file.txt"]; [fileManeger createFileAtPath:filePath contents:data attributes:nil]; //文件夹的创建 NSString *dirPath = [homePath stringByAppendingPathComponent:@"/Desktop/Apel0811"]; [fileManeger createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil]; //读取文件 NSData *fileData = [fileManager contentsAtPath:filePath2]; NSString *string = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding]); //复制文件 //目标地址必须要加上文件地址 [fileManeger copyItemAtPath:srcPath toPath:dstPath error:nil]; //剪切文件 //目标地址必须要加上文件地址 [fileManeger moveItemAtPath:srcPath toPath:dstPath error:nil]; //删除文件 [fileManeger removeItemAtPath:homePath error:nil];
文件内容操作
//写入 //写入文件内容,如果没有就会添加 NSString *str = @"hello world"; NSString *path1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/string.txt"]; [str writeToFile:path1 atomically:NO encoding:NSUTF8StringEncoding error:nil]; //写入NSDictionary NSDictionary *dic = @{ @"key1" : @"value1", @"key2" : @"value2", @"key3" : @"value3" }; NSString *path2 = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/dictionary.plist"]; [dic writeToFile:path2 atomically:YES]; //写入NSArray NSArray *array = @[@1, @2, @3]; NSString *path3 = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/array.plist"]; [array writeToFile:path3 atomically:YES]; //读取 //读取文本文件 NSString *readStr = [NSString stringWithContentsOfFile:path1 encoding:NSUTF8StringEncoding error:nil]; //读取数组文件 NSArray *readArray = [NSArray arrayWithContentsOfFile:path3]; //读取字典文件 NSDictionary *readDic = [NSDictionary dictionaryWithContentsOfFile:path2];
相关文章推荐
- AJAX 是什么?
- 20145316第四次实验报告
- 20145229《Java程序设计》第四次实验报告
- Mac OS X下搭建NDK环境
- 课堂笔记(2)
- 20145222黄亚奇《Java程序设计》第9周学习总结
- 收藏一组工业控制组件--非常实用!
- 地图定位之3D 地图
- 贝叶斯公式的背后
- an error occurred attempting to install github for windows8.1
- redis的rdb快照持久化
- Linux交叉编辑器安装
- Spring 整合 Quartz 实现动态定时任务
- 20145218 《Java程序设计》第9周学习总结
- java程序中参数值传递与引用传递问题
- android tv基础之焦点(二)
- 如何高效读论文?10位学者分享25条宝贵经验
- java 操作solr
- Swift基础03
- 深入理解Java内存模型——顺序一致性