#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// NSFileManager简单使用,文件管理类
// 1.创建对象 使用defaultManager类方法,创建单例对象(系统的单例还有NSUserDefaults, NSNotification, UIApplication,NSURLCache);
NSFileManager *fileManger = [NSFileManager defaultManager];
//创建文件夹,将要创建的/path1/path2/文件拼接到路径中
//获取Documents路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
NSLog(@"path:%@", documentPath);
NSString *newPath1 = [documentPath stringByAppendingPathComponent:@"path1"];
[fileManger createDirectoryAtPath:newPath1 withIntermediateDirectories:YES attributes:nil error:nil];
//创建文件夹里面的文件
NSString *filePath1 = [newPath1 stringByAppendingPathComponent:@"text.txt"];
BOOL file = [fileManger createFileAtPath:filePath1 contents:nil attributes:nil];
if (file) {
NSLog(@"文件创建成功");
}else{
NSLog(@"文件创建失败");
}
//往文件里面写入(也可以写入字典,数组等)
NSString *strData = @"想要写入的东西";
BOOL write = [strData writeToFile:filePath1 atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (write) {
NSLog(@"写入成功");
}else{
NSLog(@"写入失败");
}
//判断文件是否存在
if ([fileManger fileExistsAtPath:filePath1]) {
NSLog(@"存在该文件");
}else{
NSLog(@"不存在该文件");
}
//删除文件
BOOL delete = [fileManger removeItemAtPath:filePath1 error:nil];
if (delete) {
NSLog(@"文件删除成功");
}else{
NSLog(@"文件删除失败");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end