1.获取沙盒路径
NSString
*path =
NSHomeDirectory
();
// 动态获取Document目录
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//—————-------—创建文件夹------------
//创建文件管理者
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *text = @"星宇无限";
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
//创建文件,并且写入数据
BOOL success = [fileManager createFileAtPath:documentStr contents:data attributes:nil];
if (success) {
NSLog(@"创建成功");
}else {
NSLog(@"创建失败了");
//—————-------—创建文本写入内容------------
//1.创建文件管理者
NSFileManager *fileM = [NSFileManager defaultManager];
//2.创建文件,并传入数据
//2.1转为UTF8编码
NSData *data = [@"沙盒测试NO.1” dataUsingEncoding:NSUTF8StringEncoding];
//2.2字符串拼接 进入到Documents目录
NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/file.text"];
BOOL yOn = [fileM createFileAtPath:path contents:data attributes:nil];
if (yOn) {
NSLog(@"成功");
}else{
NSLog(@"失败");
}
//-------------移动文件------------
NSFileManager *fileManager = [NSFileManager defaultManager];
//当前所在的路径
NSString *atPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file.txt"];
//目标路径
NSString *toPath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Demo/file.txt"];
[fileManager moveItemAtPath:atPath toPath:toPath error:nil];
//-------------读取文件------------
//两种方式:
//方式一:
NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Demo/file.txt"];
NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];
//data->string
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"str:%@",str);
//方式二:
NSFileManager *fileManager = [NSFileManager defaultManager];
data = [fileManager contentsAtPath:filePath];
str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"str:%@",str);
//-------------获取文件属性------------
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file.txt"];
NSDictionary *dic = [fileManager attributesOfItemAtPath:filePath error:nil];
NSLog(@"dic:%@",dic);
/*
NSNumber *size = [dic objectForKey:NSFileSize];
long long value = [size longLongValue];
NSLog(@"value:%d",value);
*/
long long value = [dic fileSize];
NSLog(@"value:%d",value);
//B 1024 KB 1024 M
//-------------删除文件------------
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Demo/file.txt"];
[fileManager removeItemAtPath:filePath error:nil];