您的位置:首页 > 其它

沙盒、文件以及文件夹的操作

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];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: